This commit is contained in:
左右看
2023-06-28 00:35:46 +08:00
parent cb5bab5ce9
commit 0d848e4d07
524 changed files with 78452 additions and 12 deletions
@@ -0,0 +1,496 @@
#if !NO_INTERNALS_ACCESS
#if UNITY_2021_3_OR_NEWER
#define HAVE_BUILTIN_SHADERGRAPH
#define HAVE_CATEGORIES
#endif
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
#if HAVE_BUILTIN_SHADERGRAPH
using UnityEditor.Rendering;
using UnityEditor.Rendering.BuiltIn.ShaderGraph;
#endif
using UnityEngine;
using UnityEngine.Rendering;
namespace UnityGLTF
{
public class PBRGraphGUI :
#if HAVE_BUILTIN_SHADERGRAPH
BuiltInBaseShaderGUI
#else
ShaderGUI
#endif
{
#if UNITY_2021_1_OR_NEWER
public override void ValidateMaterial(Material material)
{
base.ValidateMaterial(material);
GLTFMaterialHelper.ValidateMaterialKeywords(material);
}
#endif
protected MaterialEditor materialEditor;
protected MaterialProperty[] properties;
private MaterialInfo currentMaterialInfo;
#if HAVE_CATEGORIES
private readonly MaterialHeaderScopeList m_MaterialScopeList = new MaterialHeaderScopeList(uint.MaxValue & ~(uint)Expandable.Advanced);
private const int ExpandableMeshProperties = 1 << 8;
private static readonly GUIContent MeshProperties = new GUIContent("Mesh Properties");
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
{
this.materialEditor = materialEditor;
this.properties = properties;
Material targetMat = materialEditor.target as Material;
if (!targetMat || !targetMat.shader) return;
if (m_FirstTimeApply)
{
OnOpenGUI(targetMat, materialEditor, properties);
m_FirstTimeApply = false;
}
// need to set these via reflection...
// m_MaterialEditor = materialEditor;
// m_Properties = properties;
if (m_MaterialEditor == null) m_MaterialEditor = typeof(BuiltInBaseShaderGUI).GetField(nameof(m_MaterialEditor), BindingFlags.Instance | BindingFlags.NonPublic);
if (m_Properties == null) m_Properties = typeof(BuiltInBaseShaderGUI).GetField(nameof(m_Properties), BindingFlags.Instance | BindingFlags.NonPublic);
m_MaterialEditor.SetValue(this, materialEditor);
m_Properties.SetValue(this, properties);
var fullPath = System.IO.Path.GetFullPath(AssetDatabase.GetAssetPath(targetMat));
var isMutable = !fullPath.Contains("Library/PackageCache") && !fullPath.Contains("Library\\PackageCache");
if (targetMat && targetMat.shader.name.StartsWith("Hidden/UnityGLTF"))
{
if (isMutable)
{
DrawFixMeBox("This is a legacy shader. Please click \"Fix\" to upgrade to PBRGraph/UnlitGraph.", MessageType.Warning, () =>
{
var isUnlit = targetMat.shader.name.Contains("Unlit");
var newShaderGuid = isUnlit ? "59541e6caf586ca4f96ccf48a4813a51" : "478ce3626be7a5f4ea58d6b13f05a2e4";
var newShader = AssetDatabase.LoadAssetAtPath<Shader>(AssetDatabase.GUIDToAssetPath(newShaderGuid));
Undo.RegisterCompleteObjectUndo(targetMat, "Convert to UnityGltf shader");
GLTFMaterialHelper.ConvertMaterialToGLTF(targetMat, targetMat.shader, newShader);
});
}
else
{
DrawFixMeBox("This is a legacy shader. Upgrade to PBRGraph/UnlitGraph for more options.", MessageType.Warning, null);
}
}
m_MaterialScopeList.DrawHeaders(materialEditor, targetMat);
}
private FieldInfo m_MaterialEditor;
private FieldInfo m_Properties;
public override void OnOpenGUI(Material material, MaterialEditor materialEditor, MaterialProperty[] properties)
{
m_MaterialScopeList.RegisterHeaderScope(Styles.SurfaceOptions, (uint)Expandable.SurfaceOptions, DrawSurfaceOptions);
m_MaterialScopeList.RegisterHeaderScope(MeshProperties, (uint)ExpandableMeshProperties, DrawGameObjectInfo);
m_MaterialScopeList.RegisterHeaderScope(Styles.SurfaceInputs, (uint)Expandable.SurfaceInputs, DrawSurfaceInputs);
m_MaterialScopeList.RegisterHeaderScope(Styles.AdvancedLabel, (uint)Expandable.Advanced, DrawAdvancedOptions);
}
#else
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
{
this.materialEditor = materialEditor;
this.properties = properties;
Material targetMat = materialEditor.target as Material;
DrawGameObjectInfo(targetMat);
#if !UNITY_2021_1_OR_NEWER
DrawSurfaceOptions(targetMat);
#endif
_DrawSurfaceInputs(targetMat);
}
#endif
private struct MaterialInfo
{
public bool hasColor;
public bool hasUV0;
public bool hasUV1;
public int occlusionTextureTexCoord;
public int baseColorTextureTexCoord;
}
private static bool HasAnyTextureAssigned(Material targetMaterial)
{
var s = targetMaterial.shader;
var propertyCount = ShaderUtil.GetPropertyCount(s);
for (var i = 0; i < propertyCount; i++)
{
if (ShaderUtil.GetPropertyType(s, i) != ShaderUtil.ShaderPropertyType.TexEnv) continue;
if (ShaderUtil.IsShaderPropertyHidden(s, i)) continue;
var tex = targetMaterial.GetTexture(ShaderUtil.GetPropertyName(s, i));
if (tex) return true;
}
return false;
}
#if !UNITY_2021_1_OR_NEWER
private static readonly Dictionary<string, string> ShaderNameToGuid = new Dictionary<string, string>()
{
{ "UnityGLTF/PBRGraph", "478ce3626be7a5f4ea58d6b13f05a2e4" },
{ "UnityGLTF/PBRGraph-Transparent", "0a931320a74ca574b91d2d7d4557dcf1" },
{ "UnityGLTF/PBRGraph-Transparent-Double", "54352a53405971b41a6587615f947085" },
{ "UnityGLTF/PBRGraph-Double", "8bc739b14fe811644abb82057b363ba8" },
{ "UnityGLTF/UnlitGraph", "59541e6caf586ca4f96ccf48a4813a51" },
{ "UnityGLTF/UnlitGraph-Transparent", "83f2caca07949794fb997734c4b0520f" },
{ "UnityGLTF/UnlitGraph-Transparent-Double", "8a8841b4fb2f63644896f4e2b36bc06d" },
{ "UnityGLTF/UnlitGraph-Double", "33ee70a7f505ddb4e80d235c3d70766d" },
};
private void DrawSurfaceOptions(Material targetMaterial)
{
EditorGUILayout.Space();
var shaderName = targetMaterial.shader.name.Replace("Hidden/", "");
var isTransparent = shaderName.Contains("-Transparent");
var isDoubleSided = shaderName.Contains("-Double");
var isCutout = targetMaterial.GetFloat("alphaCutoff") >= 0;
var indexOfDash = shaderName.IndexOf("-", StringComparison.Ordinal);
var baseShaderName = indexOfDash < 0 ? shaderName : shaderName.Substring(0, indexOfDash);
// EditorGUILayout.LabelField("Shader Name", baseShaderName);
void SetShader()
{
var newName = baseShaderName + (isTransparent ? "-Transparent" : "") + (isDoubleSided ? "-Double" : "");
Undo.RegisterCompleteObjectUndo(targetMaterial, "Set Material Options");
targetMaterial.shader = AssetDatabase.LoadAssetAtPath<Shader>(AssetDatabase.GUIDToAssetPath(ShaderNameToGuid[newName]));
var currentCutoff = targetMaterial.GetFloat("alphaCutoff");
if (!isCutout && currentCutoff == 0) currentCutoff = -0.0001f; // Hack to ensure we can actually switch states here
targetMaterial.SetFloat("alphaCutoff", Mathf.Abs(currentCutoff) * (isCutout ? 1 : -1));
}
var newT = EditorGUILayout.Toggle("Transparent", isTransparent);
if (newT != isTransparent)
{
isTransparent = newT;
SetShader();
}
var newD = EditorGUILayout.Toggle("Double Sided", isDoubleSided);
if (newD != isDoubleSided)
{
isDoubleSided = newD;
SetShader();
}
var newA = EditorGUILayout.Toggle("Cutout", isCutout);
if (newA != isCutout)
{
isCutout = newA;
SetShader();
}
EditorGUILayout.Space();
}
#endif
private void DrawGameObjectInfo(Material targetMaterial)
{
var singleSelection = Selection.objects != null && Selection.objects.Length < 2;
// Strict Mode
// - texture transforms only for baseColorTexture, is used for all others as well
// - occlusion MUST use UV2 if present
var renderer = ShaderGraphHelpers.GetRendererForMaterialEditor(materialEditor);
var haveDrawnSomething = false;
if (renderer && !singleSelection)
{
EditorGUI.BeginDisabledGroup(true);
EditorGUI.showMixedValue = true;
EditorGUILayout.ObjectField("Target Mesh", null, typeof(Mesh), true);
EditorGUI.showMixedValue = false;
EditorGUI.EndDisabledGroup();
EditorGUILayout.HelpBox("Multiple objects selected. Can't show mesh properties.", MessageType.Info);
haveDrawnSomething = true;
}
currentMaterialInfo.hasColor = true;
currentMaterialInfo.hasUV0 = true;
currentMaterialInfo.hasUV1 = true;
currentMaterialInfo.occlusionTextureTexCoord = targetMaterial.HasProperty("occlusionTextureTexCoord") ? Mathf.RoundToInt(targetMaterial.GetFloat("occlusionTextureTexCoord")) : 0;
currentMaterialInfo.baseColorTextureTexCoord = targetMaterial.HasProperty("baseColorTextureTexCoord") ? Mathf.RoundToInt(targetMaterial.GetFloat("baseColorTextureTexCoord")) : 0;
if (renderer && singleSelection)
{
var mesh = default(Mesh);
if (renderer is SkinnedMeshRenderer smr)
mesh = smr.sharedMesh;
else if (renderer is MeshRenderer mr && mr.GetComponent<MeshFilter>())
mesh = mr.GetComponent<MeshFilter>()?.sharedMesh;
if (mesh)
{
currentMaterialInfo.hasColor = mesh.HasVertexAttribute(VertexAttribute.Color);
currentMaterialInfo.hasUV0 = mesh.HasVertexAttribute(VertexAttribute.TexCoord0);
currentMaterialInfo.hasUV1 = mesh.HasVertexAttribute(VertexAttribute.TexCoord1);
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.ObjectField("Target Mesh", mesh, typeof(Mesh), true);
EditorGUILayout.Toggle("Has Vertex Colors", currentMaterialInfo.hasColor);
EditorGUI.EndDisabledGroup();
if (currentMaterialInfo.hasColor != targetMaterial.IsKeywordEnabled("_VERTEX_COLORS_ON"))
{
EditorGUI.indentLevel++;
var msg = "";
var msgType = MessageType.Info;
if (currentMaterialInfo.hasColor)
{
msg = "Mesh has vertex colors but \"Enable Vertex Colors\" is off. Exported glTF files will look different since vertex color is stored per-mesh, not per-material.";
msgType = MessageType.Warning;
}
// else
// {
// // doesn't really make sense to encourage turning vertex colors OFF - export will have them anyways.
// EditorGUILayout.HelpBox("Mesh has no vertex colors but \"Enable Vertex Colors\" is on.", MessageType.Info);
// }
if (!string.IsNullOrEmpty(msg))
{
DrawFixMeBox(msg, msgType, () =>
{
if (currentMaterialInfo.hasColor)
{
targetMaterial.EnableKeyword("_VERTEX_COLORS_ON");
targetMaterial.SetFloat("_VERTEX_COLORS", 1);
}
else
{
targetMaterial.DisableKeyword("_VERTEX_COLORS_ON");
targetMaterial.SetFloat("_VERTEX_COLORS", 0);
}
});
}
EditorGUI.indentLevel--;
}
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.Toggle("Has UV0", currentMaterialInfo.hasUV0);
EditorGUILayout.Toggle("Has UV1", currentMaterialInfo.hasUV1);
EditorGUI.EndDisabledGroup();
if (!currentMaterialInfo.hasUV0 && HasAnyTextureAssigned(targetMaterial))
{
EditorGUI.indentLevel++;
EditorGUILayout.HelpBox("This mesh has no UV coordinates but has textures assigned.", MessageType.Warning);
EditorGUI.indentLevel--;
}
if (currentMaterialInfo.hasUV1 && targetMaterial.HasProperty("occlusionTexture") && targetMaterial.GetTexture("occlusionTexture"))
{
EditorGUI.indentLevel++;
var texCoord = Mathf.RoundToInt(targetMaterial.GetFloat("occlusionTextureTexCoord"));
if (texCoord != 1)
{
DrawFixMeBox("This mesh has an Occlusion Texture and UV1 vertex data.\nWhen exporting to three.js, UV1 will be used independent of TexCoord setting.", MessageType.Warning, () =>
{
Undo.RegisterCompleteObjectUndo(targetMaterial, "Set occlusionTextureTexCoord to 1");
targetMaterial.SetFloat("occlusionTextureTexCoord", 1);
});
}
EditorGUI.indentLevel--;
}
if (!currentMaterialInfo.hasUV1)
{
if (currentMaterialInfo.baseColorTextureTexCoord > 0)
{
DrawFixMeBox("This mesh does not have UV1 vertex data but Base Texture is set to use UV1. This will lead to unexpected results.", MessageType.Warning, () =>
{
Undo.RegisterCompleteObjectUndo(targetMaterial, "Set baseColorTextureTexCoord to 0");
targetMaterial.SetFloat("baseColorTextureTexCoord", 0);
});
}
if (currentMaterialInfo.occlusionTextureTexCoord > 0)
{
DrawFixMeBox("This mesh does not have UV1 vertex data but Occlusion Texture is set to use UV1. This will lead to unexpected results.", MessageType.Warning, () =>
{
Undo.RegisterCompleteObjectUndo(targetMaterial, "Set occlusionTextureTexCoord to 0");
targetMaterial.SetFloat("occlusionTextureTexCoord", 0);
});
}
}
// check if this uses transmission
// TODO we need to expose some kind of interface so that other scripts (e.g. the rough refraction components)
// can attach to this inspector here.
/*
if (targetMaterial.IsKeywordEnabled("_VOLUME_TRANSMISSION_ON"))
{
// requires extra setup for BiRP / URP to render properly
if (!GraphicsSettings.currentRenderPipeline && !Camera.main.gameObject.GetComponent<RoughRefraction>())
{
// warn
}
else
{
// check if assigned renderer has the rough refraction feature, offer to add it otherwise
Camera.main.gameObject.GetComponent<UniversalAdditionalCameraData>()
}
}
*/
}
haveDrawnSomething = true;
}
if (targetMaterial.HasProperty("_Surface") && targetMaterial.GetFloat("_Surface") == 0 &&
targetMaterial.renderQueue <= (int) RenderQueue.AlphaTest + 50 &&
!Mathf.Approximately(targetMaterial.GetColor("baseColorFactor").a, 1))
{
DrawFixMeBox("Material is opaque but baseColorFactor has an alpha value != 1. This object might render unexpectedly in some viewers that blend results (e.g. AR, Babylon, Stager).", MessageType.Warning, () =>
{
Undo.RegisterCompleteObjectUndo(materialEditor.targets, "Set baseColorFactor.a to 1");
foreach (var t in materialEditor.targets)
{
var mat = (Material)t;
var color = mat.GetColor("baseColorFactor");
color.a = 1;
mat.SetColor("baseColorFactor", color);
EditorUtility.SetDirty(mat);
}
});
haveDrawnSomething = true;
}
if (!renderer && !haveDrawnSomething)
{
EditorGUILayout.HelpBox("Select a Renderer to see additional info", MessageType.None);
}
}
private static void DrawFixMeBox(string msg, MessageType msgType, Action action)
{
#if HAVE_BUILTIN_SHADERGRAPH && false
CoreEditorUtils.DrawFixMeBox(msg, msgType, action);
#else
EditorGUILayout.HelpBox(msg, msgType);
if (action != null && GUILayout.Button("Fix")) action();
#endif
}
#if HAVE_CATEGORIES
protected override void DrawSurfaceInputs(Material mat) => _DrawSurfaceInputs(mat);
#endif
protected void _DrawSurfaceInputs(Material mat)
{
var targetMaterial = materialEditor.target as Material;
if (!targetMaterial) return;
materialEditor.SetDefaultGUIWidths();
EditorGUI.BeginChangeCheck();
DrawProperties(targetMaterial, properties);
if (EditorGUI.EndChangeCheck())
{
foreach (var t in materialEditor.targets)
{
if (t is Material material)
GLTFMaterialHelper.ValidateMaterialKeywords(material);
}
}
}
private static bool HasPropertyButNoTex(Material targetMaterial, string name)
{
return targetMaterial.HasProperty(name) &&
#if UNITY_2021_2_OR_NEWER
targetMaterial.HasTexture(name) &&
#endif
!targetMaterial.GetTexture(name);
}
private void DrawProperties(Material targetMaterial, MaterialProperty[] properties)
{
// filter properties based on keywords
var propertyList = properties.ToList();
if (!targetMaterial.IsKeywordEnabled("_TEXTURE_TRANSFORM_ON"))
{
propertyList.RemoveAll(x => x.name.EndsWith("_ST", StringComparison.Ordinal) || x.name.EndsWith("Rotation", StringComparison.Ordinal));
}
// want to remove the _ST properties since they are drawn inline already on 2021.2+
#if UNITY_2021_2_OR_NEWER
{
propertyList.RemoveAll(x => x.name.EndsWith("_ST", StringComparison.Ordinal));
}
#endif
if (!targetMaterial.IsKeywordEnabled("_VOLUME_TRANSMISSION_ON"))
{
propertyList.RemoveAll(x => x.name.StartsWith("transmission", StringComparison.Ordinal));
}
if (!targetMaterial.HasProperty("_VOLUME_ON") || !(targetMaterial.GetFloat("_VOLUME_ON") > 0.5f))
{
propertyList.RemoveAll(x => x.name.StartsWith("thickness", StringComparison.Ordinal) || x.name.StartsWith("attenuation", StringComparison.Ordinal));
}
if (!targetMaterial.IsKeywordEnabled("_IRIDESCENCE_ON"))
{
propertyList.RemoveAll(x => x.name.StartsWith("iridescence", StringComparison.Ordinal));
}
if (!targetMaterial.IsKeywordEnabled("_SPECULAR_ON"))
{
propertyList.RemoveAll(x => x.name.StartsWith("specular", StringComparison.Ordinal));
}
if (!targetMaterial.IsKeywordEnabled("_CLEARCOAT_ON"))
{
propertyList.RemoveAll(x => x.name.StartsWith("clearcoat", StringComparison.Ordinal));
}
if (HasPropertyButNoTex(targetMaterial, "occlusionTexture"))
{
propertyList.RemoveAll(x => x.name == "occlusionStrength" || (x.name.StartsWith("occlusionTexture", StringComparison.Ordinal) && x.name != "occlusionTexture"));
}
// remove UV-related properties
if (HasPropertyButNoTex(targetMaterial, "baseColorTexture") && HasPropertyButNoTex(targetMaterial,"metallicRoughnessTexture") && HasPropertyButNoTex(targetMaterial,"normalTexture") && HasPropertyButNoTex(targetMaterial,"emissiveTexture"))
{
propertyList.RemoveAll(x => x.name.StartsWith("baseColorTexture", StringComparison.Ordinal) && x.name != "baseColorTexture");
}
if (HasPropertyButNoTex(targetMaterial,"normalTexture"))
{
propertyList.RemoveAll(x => x.name == "normalScale");
}
if (!currentMaterialInfo.hasUV0 && !currentMaterialInfo.hasUV1)
{
// hide all texture properties if no UVs
propertyList.RemoveAll(x => x.name.Contains("texture"));
}
if (!currentMaterialInfo.hasUV1 && currentMaterialInfo.occlusionTextureTexCoord == 0 && currentMaterialInfo.baseColorTextureTexCoord == 0)
{
propertyList.RemoveAll(x => x.name.EndsWith("TextureTexCoord", StringComparison.Ordinal));
}
#if UNITY_2021_1_OR_NEWER
var isBirp = !GraphicsSettings.currentRenderPipeline;
if ((isBirp && !targetMaterial.IsKeywordEnabled("_BUILTIN_ALPHATEST_ON")) ||
(!isBirp && !targetMaterial.IsKeywordEnabled("_ALPHATEST_ON")))
#else
if (targetMaterial.GetFloat("alphaCutoff") < 0)
#endif
{
propertyList.RemoveAll(x => x.name == "alphaCutoff");
}
// TODO we probably want full manual control, all this internal access is horrible...
// E.g. impossible to render inline texture properties...
ShaderGraphHelpers.DrawShaderGraphGUI(materialEditor, propertyList);
}
public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
{
GLTFMaterialHelper.ConvertMaterialToGLTF(material, oldShader, newShader);
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7fd38ac84daf5a14180dde4bc5949e25
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,56 @@
#if !NO_INTERNALS_ACCESS
#if UNITY_2021_3_OR_NEWER
#define HAVE_CATEGORIES
#endif
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
#if HAVE_CATEGORIES
using UnityEditor.ShaderGraph.Drawing;
#endif
using UnityEngine;
using Object = UnityEngine.Object;
namespace UnityGLTF
{
public static class ShaderGraphHelpers
{
public static void DrawShaderGraphGUI(MaterialEditor materialEditor, IEnumerable<MaterialProperty> properties)
{
#if HAVE_CATEGORIES
ShaderGraphPropertyDrawers.DrawShaderGraphGUI(materialEditor, properties);
#else
materialEditor.PropertiesDefaultGUI(properties.ToArray());
#endif
}
private static Type propertyView;
private static PropertyInfo propertyViewer;
private static PropertyInfo tracker;
// matches logic in MaterialEditor.ShouldEditorBeHidden to find the right renderer this material is inspected on.
public static Renderer GetRendererForMaterialEditor(MaterialEditor materialEditor)
{
if (propertyViewer == null) propertyViewer = typeof(Editor).GetProperty(nameof(propertyViewer), BindingFlags.Instance | BindingFlags.NonPublic);
if (propertyView == null) propertyView = typeof(Editor).Assembly.GetType("UnityEditor.IPropertyView");
if (tracker == null) tracker = propertyView?.GetProperty("tracker", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
var iPropertyViewer = propertyViewer?.GetValue(materialEditor) as Object;
if (!iPropertyViewer) return null;
var editorTracker = tracker?.GetValue(iPropertyViewer) as ActiveEditorTracker;
if (editorTracker == null) return null;
GameObject target = editorTracker.activeEditors[0].target as GameObject;
if (!target) return null;
Renderer c = target.GetComponent<MeshRenderer>();
if (!c) c = target.GetComponent<SkinnedMeshRenderer>();
return c;
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0a60cd145bbb31542ab7932da93de3f3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,105 @@
#if !NO_INTERNALS_ACCESS && UNITY_2020_1_OR_NEWER
using System.IO;
using UnityEditor;
using UnityEditor.ShaderGraph;
using UnityEngine;
#if UNITY_2020_2_OR_NEWER
using UnityEditor.AssetImporters;
#else
using UnityEditor.Experimental.AssetImporters;
#endif
namespace UnityGLTF
{
[ScriptedImporter(0, ".override-graph", -500)]
internal class ShaderGraphOverrideImporter : ShaderGraphImporter, IUnityGltfShaderUpgradeMeta
{
[HideInInspector]
public Shader sourceShader;
[HideInInspector]
public Shader upgradeShader;
public bool forceTransparent = true;
public bool forceDoublesided = false;
public bool hideShader = true;
public Shader SourceShader => sourceShader;
public bool IsTransparent => forceTransparent;
public bool IsDoublesided => forceDoublesided;
public bool IsUnlit => sourceShader.name.Contains("Unlit");
public override void OnImportAsset(AssetImportContext ctx)
{
if (!sourceShader)
return;
#if UNITY_2021_1_OR_NEWER && false
// we don't need extra shaders on 2021.1+,
// as Shader Graph allows overriding the material properties there.
// but we do want to allow upgrading the materials, so we need to import something and allow upgrading through ShaderGraphUpdater
var meta = ScriptableObject.CreateInstance<UnityGltfShaderUpgradeMeta>();
meta.name = "Shader Upgrade Meta";
meta.hideFlags = HideFlags.HideInInspector;
meta.sourceShader = sourceShader;
meta.isTransparent = forceTransparent;
meta.isDoublesided = forceDoublesided;
const string shaderName = "Hidden/UnityGltf/UpgradeShader";
var shaderText = File.ReadAllText(AssetDatabase.GetAssetPath(upgradeShader))
.Replace(shaderName, shaderName + meta.GenerateNameString());
var shader = ShaderUtil.CreateShaderAsset(ctx, shaderText, true);
ctx.AddObjectToAsset("MainAsset", shader);
ctx.AddObjectToAsset("UpgradeMeta", meta);
ctx.SetMainObject(shader);
#else
// cache write time, we want to reset the file again afterwards
var lastWriteTimeUtc = File.GetLastWriteTimeUtc(ctx.assetPath);
var path = AssetDatabase.GetAssetPath(sourceShader);
ctx.DependsOnArtifact(AssetDatabase.GUIDFromAssetPath(path));
var graphData = File.ReadAllText(path);
#if UNITY_2021_1_OR_NEWER
// disable material overrides on 2021.1+ - we want people to use the proper shader for that
graphData = graphData.Replace("\"m_AllowMaterialOverride\": true", "\"m_AllowMaterialOverride\": false");
#endif
// modify:
// switch to transparent
if (forceTransparent)
graphData = graphData.Replace("\"m_SurfaceType\": 0", "\"m_SurfaceType\": 1");
// for 2021+
// if (forceDoublesided)
// graphData = graphData
// .Replace("\"m_RenderFace\": 2", "\"m_RenderFace\": 0")
// .Replace("\"m_RenderFace\": 1", "\"m_RenderFace\": 0");
// for 2020+
if (forceDoublesided && !graphData.Contains("m_TwoSided"))
graphData = graphData
.Replace("\"m_SurfaceType\": 0", "\"m_SurfaceType\": 0" + ",\n" + "\"m_TwoSided\": true")
.Replace("\"m_SurfaceType\": 1", "\"m_SurfaceType\": 1" + ",\n" + "\"m_TwoSided\": true");
if (hideShader)
graphData = graphData.Replace("\"m_Path\": \"", "\"m_Path\": \"Hidden/");
File.WriteAllText(ctx.assetPath, graphData);
// run import on the modified shader
base.OnImportAsset(ctx);
// clean the file on disk again
File.WriteAllText(ctx.assetPath, "");
// reset write time to what it was before - avoids AssetDB reload
File.SetLastWriteTimeUtc(ctx.assetPath, lastWriteTimeUtc);
#endif
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fe431e399c52971408121c6c40cde979
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,26 @@
#if !NO_INTERNALS_ACCESS && UNITY_2020_1_OR_NEWER
using UnityEditor;
#if UNITY_2020_2_OR_NEWER
using UnityEditor.AssetImporters;
#else
using UnityEditor.Experimental.AssetImporters;
#endif
namespace UnityGLTF
{
[CustomEditor(typeof(ShaderGraphOverrideImporter))]
class ShaderGraphOverrideImporterEditor : ScriptedImporterEditor
{
public override void OnInspectorGUI()
{
#if UNITY_2021_1_OR_NEWER
EditorGUILayout.HelpBox("Deprecated. Use material overrides on UnityGLTF/PBRGraph and UnityGLTF/UnlitGraph instead of separate shaders.", MessageType.Warning);
#endif
DrawDefaultInspector();
ApplyRevertGUI();
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 511b21f4c3344c54689aed102b11724a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
{
"reference": "GUID:be0903cd8e1546f498710afdc59db5eb"
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: d60ff41bbebf9024dac1e4f0dc004a57
AssemblyDefinitionReferenceImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant: