bug fix
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
[CustomEditor(typeof(GLTFComponent))]
|
||||
public class GLTFComponentInspector : Editor
|
||||
{
|
||||
private Vector2 scrollPosition = Vector2.zero;
|
||||
|
||||
public override void OnInspectorGUI()
|
||||
{
|
||||
DrawDefaultInspector();
|
||||
serializedObject.ApplyModifiedProperties();
|
||||
|
||||
#if UNITY_ANIMATION
|
||||
var gltfComponent = serializedObject.targetObject as GLTFComponent;
|
||||
if (gltfComponent != null && gltfComponent.Animations != null)
|
||||
{
|
||||
EditorGUILayout.LabelField("Animations:");
|
||||
using (var scrollView = new EditorGUILayout.ScrollViewScope(scrollPosition))
|
||||
{
|
||||
scrollPosition = scrollView.scrollPosition;
|
||||
foreach (var animation in gltfComponent.Animations)
|
||||
{
|
||||
DrawAnimation(animation);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private void DrawAnimation(Animation animation)
|
||||
{
|
||||
GUILayout.Label(animation.name);
|
||||
|
||||
foreach (AnimationState animationState in animation)
|
||||
{
|
||||
using (new EditorGUILayout.HorizontalScope())
|
||||
{
|
||||
var clip = animationState.clip;
|
||||
var clipName = clip.name;
|
||||
GUILayout.Label(clipName);
|
||||
|
||||
var isPlaying = animation.IsPlaying(clipName);
|
||||
string playPause = isPlaying ? "pause" : "play";
|
||||
|
||||
var buttonPressed = GUILayout.Button(playPause);
|
||||
|
||||
if (buttonPressed)
|
||||
{
|
||||
if (isPlaying)
|
||||
{
|
||||
animation.Stop(clipName);
|
||||
}
|
||||
else
|
||||
{
|
||||
animation.Play(clipName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void SetClipsPlaying(Animation animation, bool play)
|
||||
{
|
||||
foreach (AnimationState animationState in animation)
|
||||
{
|
||||
if (play)
|
||||
{
|
||||
animation.Play(animationState.clip.name);
|
||||
}
|
||||
else
|
||||
{
|
||||
animation.Stop(animationState.clip.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 843e1771f80e49643aed2baa52c2394d
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.SceneManagement;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public static class GLTFExportMenu
|
||||
{
|
||||
private const string MenuPrefix = "Assets/UnityGLTF/";
|
||||
|
||||
public static string RetrieveTexturePath(UnityEngine.Texture texture)
|
||||
{
|
||||
var path = AssetDatabase.GetAssetPath(texture);
|
||||
// texture is a subasset
|
||||
if (AssetDatabase.GetMainAssetTypeAtPath(path) != typeof(Texture2D))
|
||||
{
|
||||
var ext = System.IO.Path.GetExtension(path);
|
||||
if (string.IsNullOrWhiteSpace(ext)) return texture.name + ".png";
|
||||
path = path.Replace(ext, "-" + texture.name + ext);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private static bool TryGetExportNameAndRootTransformsFromSelection(out string sceneName, out Transform[] rootTransforms)
|
||||
{
|
||||
if (Selection.transforms.Length > 1)
|
||||
{
|
||||
sceneName = SceneManager.GetActiveScene().name;
|
||||
rootTransforms = Selection.transforms;
|
||||
return true;
|
||||
}
|
||||
if (Selection.transforms.Length == 1)
|
||||
{
|
||||
sceneName = Selection.activeGameObject.name;
|
||||
rootTransforms = Selection.transforms;
|
||||
return true;
|
||||
}
|
||||
if (Selection.objects.Any() && Selection.objects.All(x => x is GameObject))
|
||||
{
|
||||
sceneName = Selection.objects.First().name;
|
||||
rootTransforms = Selection.objects.Select(x => (x as GameObject).transform).ToArray();
|
||||
return true;
|
||||
}
|
||||
|
||||
sceneName = null;
|
||||
rootTransforms = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
[MenuItem(MenuPrefix + "Export selected as glTF", true)]
|
||||
private static bool ExportSelectedValidate()
|
||||
{
|
||||
return TryGetExportNameAndRootTransformsFromSelection(out _, out _);
|
||||
}
|
||||
|
||||
[MenuItem(MenuPrefix + "Export selected as glTF")]
|
||||
private static void ExportSelected()
|
||||
{
|
||||
if (!TryGetExportNameAndRootTransformsFromSelection(out var sceneName, out var rootTransforms))
|
||||
{
|
||||
Debug.LogError("Can't export: selection is empty");
|
||||
return;
|
||||
}
|
||||
|
||||
Export(rootTransforms, false, sceneName);
|
||||
}
|
||||
|
||||
[MenuItem(MenuPrefix + "Export selected as GLB", true)]
|
||||
private static bool ExportGLBSelectedValidate()
|
||||
{
|
||||
return TryGetExportNameAndRootTransformsFromSelection(out _, out _);
|
||||
}
|
||||
|
||||
[MenuItem(MenuPrefix + "Export selected as GLB")]
|
||||
private static void ExportGLBSelected()
|
||||
{
|
||||
if (!TryGetExportNameAndRootTransformsFromSelection(out var sceneName, out var rootTransforms))
|
||||
{
|
||||
Debug.LogError("Can't export: selection is empty");
|
||||
return;
|
||||
}
|
||||
Export(rootTransforms, true, sceneName);
|
||||
}
|
||||
|
||||
[MenuItem(MenuPrefix + "Export active scene as glTF")]
|
||||
private static void ExportScene()
|
||||
{
|
||||
var scene = SceneManager.GetActiveScene();
|
||||
var gameObjects = scene.GetRootGameObjects();
|
||||
var transforms = Array.ConvertAll(gameObjects, gameObject => gameObject.transform);
|
||||
|
||||
Export(transforms, false, scene.name);
|
||||
}
|
||||
|
||||
[MenuItem(MenuPrefix + "Export active scene as GLB")]
|
||||
private static void ExportSceneGLB()
|
||||
{
|
||||
var scene = SceneManager.GetActiveScene();
|
||||
var gameObjects = scene.GetRootGameObjects();
|
||||
var transforms = Array.ConvertAll(gameObjects, gameObject => gameObject.transform);
|
||||
|
||||
Export(transforms, true, scene.name);
|
||||
}
|
||||
|
||||
private static void Export(Transform[] transforms, bool binary, string sceneName)
|
||||
{
|
||||
var settings = GLTFSettings.GetOrCreateSettings();
|
||||
var exportOptions = new ExportOptions { TexturePathRetriever = RetrieveTexturePath };
|
||||
var exporter = new GLTFSceneExporter(transforms, exportOptions);
|
||||
|
||||
var invokedByShortcut = Event.current?.type == EventType.KeyDown;
|
||||
var path = settings.SaveFolderPath;
|
||||
if (!invokedByShortcut || !Directory.Exists(path))
|
||||
path = EditorUtility.SaveFolderPanel("glTF Export Path", settings.SaveFolderPath, "");
|
||||
|
||||
if (!string.IsNullOrEmpty(path))
|
||||
{
|
||||
var ext = binary ? ".glb" : ".gltf";
|
||||
var resultFile = GLTFSceneExporter.GetFileName(path, sceneName, ext);
|
||||
settings.SaveFolderPath = path;
|
||||
if(binary)
|
||||
exporter.SaveGLB(path, sceneName);
|
||||
else
|
||||
exporter.SaveGLTFandBin(path, sceneName);
|
||||
|
||||
Debug.Log("Exported to " + resultFile);
|
||||
EditorUtility.RevealInFinder(resultFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fd3d2ca14e7c1084888c77f15c69ae56
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,619 @@
|
||||
#if UNITY_2017_1_OR_NEWER
|
||||
|
||||
// glTFast is on the path to being official, so it should have highest priority as importer by default
|
||||
// This ifdef is included for completeness.
|
||||
// Other glTF importers should specify this via AsmDef dependency, for example
|
||||
// `com.atteneder.gltfast@3.0.0: HAVE_GLTFAST` and then checking here `#if HAVE_GLTFAST`
|
||||
#if HAVE_GLTFAST
|
||||
#define ANOTHER_IMPORTER_HAS_HIGHER_PRIORITY
|
||||
#endif
|
||||
|
||||
#if !ANOTHER_IMPORTER_HAS_HIGHER_PRIORITY && !UNITYGLTF_FORCE_DEFAULT_IMPORTER_OFF
|
||||
#define ENABLE_DEFAULT_GLB_IMPORTER
|
||||
#endif
|
||||
#if UNITYGLTF_FORCE_DEFAULT_IMPORTER_ON
|
||||
#define ENABLE_DEFAULT_GLB_IMPORTER
|
||||
#endif
|
||||
|
||||
using UnityEditor;
|
||||
using System.IO;
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System;
|
||||
using Object = UnityEngine.Object;
|
||||
using UnityGLTF.Loader;
|
||||
using GLTF.Schema;
|
||||
using GLTF;
|
||||
using Unity.Collections;
|
||||
#if UNITY_2020_2_OR_NEWER
|
||||
using UnityEditor.AssetImporters;
|
||||
#else
|
||||
using UnityEditor.Experimental.AssetImporters;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
#if UNITY_2020_2_OR_NEWER
|
||||
#if ENABLE_DEFAULT_GLB_IMPORTER
|
||||
[ScriptedImporter(ImporterVersion, new[] { "glb", "gltf" })]
|
||||
#else
|
||||
[ScriptedImporter(ImporterVersion, null, overrideExts: new[] { "glb", "gltf" })]
|
||||
#endif
|
||||
#else
|
||||
[ScriptedImporter(ImporterVersion, new[] { "glb" })]
|
||||
#endif
|
||||
public class GLTFImporter : ScriptedImporter
|
||||
{
|
||||
private const int ImporterVersion = 7;
|
||||
|
||||
private static void EnsureShadersAreLoaded()
|
||||
{
|
||||
const string PackagePrefix = "Packages/org.khronos.unitygltf/";
|
||||
var shaders = new string[] {
|
||||
PackagePrefix + "Runtime/Shaders/ShaderGraph/PBRGraph.shadergraph",
|
||||
PackagePrefix + "Runtime/Shaders/ShaderGraph/UnlitGraph.shadergraph",
|
||||
PackagePrefix + "Runtime/Shaders/PbrMetallicRoughness.shader",
|
||||
PackagePrefix + "Runtime/Shaders/PbrSpecularGlossiness.shader",
|
||||
PackagePrefix + "Runtime/Shaders/Unlit.shader",
|
||||
};
|
||||
|
||||
foreach (var shaderPath in shaders)
|
||||
{
|
||||
AssetDatabase.LoadAssetAtPath<Shader>(shaderPath);
|
||||
}
|
||||
}
|
||||
|
||||
[Tooltip("Turn this off to create an explicit GameObject for the glTF scene. A scene root will always be created if there's more than one root node.")]
|
||||
[SerializeField] internal bool _removeEmptyRootObjects = true;
|
||||
[SerializeField] internal float _scaleFactor = 1.0f;
|
||||
[SerializeField] internal int _maximumLod = 300;
|
||||
[SerializeField] internal bool _readWriteEnabled = true;
|
||||
[SerializeField] internal bool _generateColliders = false;
|
||||
[SerializeField] internal bool _swapUvs = false;
|
||||
[SerializeField] internal bool _generateLightmapUVs = false;
|
||||
[SerializeField] internal GLTFImporterNormals _importNormals = GLTFImporterNormals.Import;
|
||||
[SerializeField] internal GLTFImporterNormals _importTangents = GLTFImporterNormals.Import;
|
||||
[SerializeField] internal AnimationMethod _importAnimations = AnimationMethod.Mecanim;
|
||||
[SerializeField] internal bool _addAnimatorComponent = false;
|
||||
[SerializeField] internal bool _animationLoopTime = true;
|
||||
[SerializeField] internal bool _animationLoopPose = false;
|
||||
[SerializeField] internal bool _importMaterials = true;
|
||||
[Tooltip("Enable this to get the same main asset identifiers as glTFast uses. This is recommended for new asset imports. Note that changing this for already imported assets will break their scene references and require manually re-adding the affected assets.")]
|
||||
[SerializeField] internal bool _useSceneNameIdentifier = false;
|
||||
|
||||
// for humanoid importer
|
||||
[SerializeField] internal bool m_OptimizeGameObjects = false;
|
||||
[SerializeField] internal HumanDescription m_HumanDescription = new HumanDescription();
|
||||
|
||||
// material remapping
|
||||
[SerializeField] private Material[] m_Materials = new Material[0];
|
||||
|
||||
[Serializable]
|
||||
internal class ExtensionInfo
|
||||
{
|
||||
public string name;
|
||||
public bool supported;
|
||||
public bool used;
|
||||
public bool required;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class TextureInfo
|
||||
{
|
||||
public Texture2D texture;
|
||||
public bool shouldBeLinear;
|
||||
}
|
||||
|
||||
#if !UNIYT_2020_2_OR_NEWER
|
||||
private class NonReorderableAttribute : Attribute {}
|
||||
#endif
|
||||
|
||||
// Import messages (extensions, warnings, errors, ...)
|
||||
[NonReorderable] [SerializeField] internal List<ExtensionInfo> _extensions;
|
||||
[NonReorderable] [SerializeField] private List<TextureInfo> _textures;
|
||||
[SerializeField] internal string _mainAssetIdentifier;
|
||||
|
||||
internal List<TextureInfo> Textures => _textures;
|
||||
|
||||
private static string[] GatherDependenciesFromSourceFile(string path)
|
||||
{
|
||||
// only supported glTF for now - would be harder to check for external references in glb assets.
|
||||
if (!path.ToLowerInvariant().EndsWith(".gltf")) return Array.Empty<string>();
|
||||
|
||||
var dependencies = new List<string>();
|
||||
|
||||
// read minimal JSON, check if there's a bin buffer, and load that.
|
||||
// all other assets should be "proper assets" and be found by the asset database, but we're not importing .bin
|
||||
// since it's too common as a file type.
|
||||
var gltf = GLTFRoot.Deserialize(new StreamReader(path));
|
||||
var externalBuffers = gltf?.Buffers?.Where(b => b?.Uri != null && b.Uri.ToLowerInvariant().EndsWith(".bin"));
|
||||
if (externalBuffers != null)
|
||||
{
|
||||
var dir = Path.GetDirectoryName(path);
|
||||
foreach (var buffer in externalBuffers)
|
||||
{
|
||||
var uri = buffer.Uri;
|
||||
if (!File.Exists(Path.Combine(dir, uri)))
|
||||
uri = Uri.UnescapeDataString(uri);
|
||||
if (File.Exists(Path.Combine(dir, uri)))
|
||||
dependencies.Add(Path.Combine(dir, uri));
|
||||
// TODO check if inside the project/any package, could be an absolute path
|
||||
else if (File.Exists(uri))
|
||||
dependencies.Add(uri);
|
||||
}
|
||||
}
|
||||
|
||||
return dependencies.ToArray();
|
||||
}
|
||||
|
||||
public override void OnImportAsset(AssetImportContext ctx)
|
||||
{
|
||||
string sceneName = null;
|
||||
GameObject gltfScene = null;
|
||||
AnimationClip[] animations = null;
|
||||
Mesh[] meshes = null;
|
||||
|
||||
var uniqueNames = new List<string>() { "main asset" };
|
||||
EnsureShadersAreLoaded();
|
||||
|
||||
string GetUniqueName(string desiredName)
|
||||
{
|
||||
var uniqueName = ObjectNames.GetUniqueName(uniqueNames.ToArray(), desiredName);
|
||||
if (!uniqueNames.Contains(uniqueName)) uniqueNames.Add(uniqueName);
|
||||
return uniqueName;
|
||||
}
|
||||
|
||||
#if UNITY_2017_3_OR_NEWER
|
||||
// We explicitly turn the new identifier on for new imports, that is, when no meta file existed before this import.
|
||||
// We do this early, so that when imports fail, we still get the new identifier. Unity already sets import settings on failed imports.
|
||||
if (!_useSceneNameIdentifier)
|
||||
{
|
||||
var importer = GetAtPath(ctx.assetPath);
|
||||
if (importer.importSettingsMissing)
|
||||
{
|
||||
_useSceneNameIdentifier = true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
try
|
||||
{
|
||||
sceneName = Path.GetFileNameWithoutExtension(ctx.assetPath);
|
||||
CreateGLTFScene(ctx.assetPath, out gltfScene, out animations);
|
||||
var rootGltfComponent = gltfScene.GetComponent<InstantiatedGLTFObject>();
|
||||
if (rootGltfComponent) DestroyImmediate(rootGltfComponent);
|
||||
|
||||
// Remove empty roots
|
||||
if (_removeEmptyRootObjects)
|
||||
{
|
||||
var t = gltfScene.transform;
|
||||
var existingAnimator = t.GetComponent<Animator>();
|
||||
var hadAnimator = (bool)existingAnimator;
|
||||
var existingAvatar = existingAnimator ? existingAnimator.avatar : default;
|
||||
if (existingAnimator)
|
||||
DestroyImmediate(existingAnimator);
|
||||
|
||||
while (
|
||||
gltfScene.transform.childCount == 1 &&
|
||||
gltfScene.GetComponents<Component>().Length == 1)
|
||||
{
|
||||
var parent = gltfScene;
|
||||
var importName = parent.name;
|
||||
gltfScene = gltfScene.transform.GetChild(0).gameObject;
|
||||
gltfScene.name = importName; // root name is always name of the file anyways
|
||||
t = gltfScene.transform;
|
||||
t.parent = null; // To keep transform information in the new parent
|
||||
DestroyImmediate(parent); // Get rid of the parent
|
||||
}
|
||||
|
||||
// Re-add animator if it was removed
|
||||
if (hadAnimator)
|
||||
{
|
||||
var newAnimator = gltfScene.AddComponent<Animator>();
|
||||
newAnimator.avatar = existingAvatar;
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure there are no hide flags present (will cause problems when saving)
|
||||
gltfScene.hideFlags &= ~(HideFlags.HideAndDontSave);
|
||||
foreach (Transform child in gltfScene.transform)
|
||||
{
|
||||
child.gameObject.hideFlags &= ~(HideFlags.HideAndDontSave);
|
||||
}
|
||||
|
||||
// scale all localPosition values if necessary
|
||||
if (!Mathf.Approximately(_scaleFactor, 1))
|
||||
{
|
||||
var transforms = gltfScene.GetComponentsInChildren<Transform>();
|
||||
foreach (var tr in transforms)
|
||||
{
|
||||
tr.localPosition *= _scaleFactor;
|
||||
}
|
||||
}
|
||||
|
||||
// Get meshes
|
||||
var meshHash = new HashSet<UnityEngine.Mesh>();
|
||||
var meshFilters = gltfScene.GetComponentsInChildren<MeshFilter>().Select(x => (x.gameObject, x.sharedMesh)).ToList();
|
||||
meshFilters.AddRange(gltfScene.GetComponentsInChildren<SkinnedMeshRenderer>().Select(x => (x.gameObject, x.sharedMesh)));
|
||||
var vertexBuffer = new List<Vector3>();
|
||||
meshes = meshFilters.Select(mf =>
|
||||
{
|
||||
var mesh = mf.sharedMesh;
|
||||
|
||||
if (meshHash.Contains(mesh))
|
||||
return null;
|
||||
meshHash.Add(mesh);
|
||||
|
||||
if (!Mathf.Approximately(_scaleFactor, 1.0f))
|
||||
{
|
||||
vertexBuffer.Clear();
|
||||
mesh.GetVertices(vertexBuffer);
|
||||
for (var i = 0; i < vertexBuffer.Count; ++i)
|
||||
{
|
||||
vertexBuffer[i] *= _scaleFactor;
|
||||
}
|
||||
mesh.SetVertices(vertexBuffer);
|
||||
}
|
||||
if (_generateLightmapUVs)
|
||||
{
|
||||
var uv2 = mesh.uv2;
|
||||
if (uv2 == null || uv2.Length < 1)
|
||||
{
|
||||
var hasTriangleTopology = true;
|
||||
for (var i = 0; i < mesh.subMeshCount; i++)
|
||||
hasTriangleTopology &= mesh.GetTopology(i) == MeshTopology.Triangles;
|
||||
|
||||
// uv2 = Unwrapping.GeneratePerTriangleUV(mesh);
|
||||
// mesh.SetUVs(1, uv2);
|
||||
|
||||
// There seems to be a bug in Unity's splitting code:
|
||||
// for some meshes, the result is broken after splitting.
|
||||
if (hasTriangleTopology)
|
||||
Unwrapping.GenerateSecondaryUVSet(mesh);
|
||||
}
|
||||
}
|
||||
if (_swapUvs)
|
||||
{
|
||||
var uv = mesh.uv;
|
||||
var uv2 = mesh.uv2;
|
||||
mesh.uv = uv2;
|
||||
if(uv.Length > 0)
|
||||
mesh.uv2 = uv;
|
||||
}
|
||||
|
||||
if (_importNormals == GLTFImporterNormals.None)
|
||||
mesh.normals = new Vector3[0];
|
||||
else if (_importNormals == GLTFImporterNormals.Calculate && mesh.GetTopology(0) == MeshTopology.Triangles)
|
||||
mesh.RecalculateNormals();
|
||||
else if (_importNormals == GLTFImporterNormals.Import && mesh.normals.Length == 0 && mesh.GetTopology(0) == MeshTopology.Triangles)
|
||||
mesh.RecalculateNormals();
|
||||
|
||||
if (_importTangents == GLTFImporterNormals.None)
|
||||
mesh.tangents = new Vector4[0];
|
||||
else if (_importTangents == GLTFImporterNormals.Calculate && mesh.GetTopology(0) == MeshTopology.Triangles)
|
||||
mesh.RecalculateTangents();
|
||||
else if (_importTangents == GLTFImporterNormals.Import && mesh.tangents.Length == 0 && mesh.GetTopology(0) == MeshTopology.Triangles)
|
||||
mesh.RecalculateTangents();
|
||||
|
||||
mesh.UploadMeshData(!_readWriteEnabled);
|
||||
|
||||
if (_generateColliders)
|
||||
{
|
||||
var collider = mf.gameObject.AddComponent<MeshCollider>();
|
||||
collider.sharedMesh = mesh;
|
||||
}
|
||||
|
||||
return mesh;
|
||||
}).Where(x => x).ToArray();
|
||||
|
||||
if (animations != null)
|
||||
{
|
||||
foreach (var clip in animations)
|
||||
{
|
||||
ctx.AddObjectToAsset(GetUniqueName(clip.name), clip);
|
||||
}
|
||||
}
|
||||
|
||||
// we can't add the Animators as subassets here, since they require their state machines to be direct subassets themselves.
|
||||
// foreach (var anim in animators)
|
||||
// {
|
||||
// ctx.AddObjectToAsset(GetUniqueName(anim.runtimeAnimatorController.name), anim.runtimeAnimatorController as AnimatorController);
|
||||
// foreach (var layer in (anim.runtimeAnimatorController as AnimatorController).layers)
|
||||
// {
|
||||
// ctx.AddObjectToAsset(GetUniqueName(layer.name + "-state"), layer.stateMachine);
|
||||
// }
|
||||
// }
|
||||
|
||||
if (_importAnimations == AnimationMethod.MecanimHumanoid)
|
||||
{
|
||||
var avatar = HumanoidSetup.AddAvatarToGameObject(gltfScene);
|
||||
if (avatar && avatar.isValid)
|
||||
ctx.AddObjectToAsset("avatar", avatar);
|
||||
}
|
||||
|
||||
var renderers = gltfScene.GetComponentsInChildren<Renderer>();
|
||||
|
||||
if (_importMaterials)
|
||||
{
|
||||
// Get materials
|
||||
var map = GetExternalObjectMap();
|
||||
var materialHash = new HashSet<UnityEngine.Material>();
|
||||
var materials = renderers.SelectMany(r =>
|
||||
{
|
||||
return r.sharedMaterials.Select(mat =>
|
||||
{
|
||||
if (materialHash.Add(mat))
|
||||
{
|
||||
var matName = string.IsNullOrEmpty(mat.name) ? mat.shader.name : mat.name;
|
||||
if (matName == mat.shader.name)
|
||||
{
|
||||
matName = matName.Substring(Mathf.Min(matName.LastIndexOf("/", StringComparison.Ordinal) + 1, matName.Length - 1));
|
||||
}
|
||||
mat.name = matName;
|
||||
}
|
||||
|
||||
return mat;
|
||||
});
|
||||
}).Distinct().ToArray();
|
||||
|
||||
// apply material remap
|
||||
foreach(var r in renderers)
|
||||
{
|
||||
// remap materials to external objects
|
||||
var m = r.sharedMaterials;
|
||||
for (var i = 0; i < m.Length; i++)
|
||||
{
|
||||
var si = new SourceAssetIdentifier(m[i]);
|
||||
if (map.ContainsKey(si))
|
||||
m[i] = map[si] as Material;
|
||||
}
|
||||
r.sharedMaterials = m;
|
||||
};
|
||||
|
||||
// Get textures
|
||||
var textureHash = new HashSet<Texture2D>();
|
||||
var texMaterialMap = new Dictionary<Texture2D, List<TexMaterialMap>>();
|
||||
var textures = materials.SelectMany(mat =>
|
||||
{
|
||||
var shader = mat.shader;
|
||||
if (!shader) return Enumerable.Empty<Texture2D>();
|
||||
|
||||
var matTextures = new List<Texture2D>();
|
||||
for (var i = 0; i < ShaderUtil.GetPropertyCount(shader); ++i)
|
||||
{
|
||||
if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv)
|
||||
{
|
||||
var propertyName = ShaderUtil.GetPropertyName(shader, i);
|
||||
var tex = mat.GetTexture(propertyName) as Texture2D;
|
||||
if (tex)
|
||||
{
|
||||
if (textureHash.Add(tex))
|
||||
{
|
||||
var texName = tex.name;
|
||||
if (string.IsNullOrEmpty(texName))
|
||||
{
|
||||
if (propertyName.StartsWith("_")) texName = propertyName.Substring(Mathf.Min(1, propertyName.Length - 1));
|
||||
tex.name = texName;
|
||||
}
|
||||
matTextures.Add(tex);
|
||||
}
|
||||
|
||||
List<TexMaterialMap> materialMaps;
|
||||
if (!texMaterialMap.TryGetValue(tex, out materialMaps))
|
||||
{
|
||||
materialMaps = new List<TexMaterialMap>();
|
||||
texMaterialMap.Add(tex, materialMaps);
|
||||
}
|
||||
|
||||
materialMaps.Add(new TexMaterialMap(mat, propertyName, propertyName == "_BumpMap" || propertyName == "normalTexture" || propertyName.EndsWith("NormalTexture")));
|
||||
}
|
||||
}
|
||||
}
|
||||
return matTextures;
|
||||
}).Distinct().ToArray();
|
||||
|
||||
// Save textures as separate assets and rewrite refs
|
||||
// TODO: Support for other texture types
|
||||
if (textures.Length > 0)
|
||||
{
|
||||
foreach (var tex in textures)
|
||||
{
|
||||
if (AssetDatabase.Contains(tex) && AssetDatabase.GetAssetPath(tex) != ctx.assetPath)
|
||||
{
|
||||
#if UNITY_2020_2_OR_NEWER
|
||||
ctx.DependsOnArtifact(
|
||||
#else
|
||||
ctx.DependsOnSourceAsset(
|
||||
#endif
|
||||
AssetDatabase.GetAssetPath(tex));
|
||||
}
|
||||
else
|
||||
{
|
||||
ctx.AddObjectToAsset(GetUniqueName(tex.name), tex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !UNITY_2022_1_OR_NEWER
|
||||
AssetDatabase.Refresh();
|
||||
#endif
|
||||
|
||||
// Save materials as separate assets and rewrite refs
|
||||
if (materials.Length > 0)
|
||||
{
|
||||
foreach (var mat in materials)
|
||||
{
|
||||
// ensure materials that are overriden aren't shown in the hierarchy.
|
||||
var si = new SourceAssetIdentifier(mat);
|
||||
if (map.ContainsKey(si))
|
||||
mat.hideFlags = HideFlags.HideInHierarchy | HideFlags.HideInInspector;
|
||||
|
||||
ctx.AddObjectToAsset(GetUniqueName(mat.name), mat);
|
||||
}
|
||||
}
|
||||
|
||||
m_Materials = materials;
|
||||
|
||||
#if !UNITY_2022_1_OR_NEWER
|
||||
AssetDatabase.SaveAssets();
|
||||
AssetDatabase.Refresh();
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
var temp = GameObject.CreatePrimitive(PrimitiveType.Plane);
|
||||
temp.SetActive(false);
|
||||
var defaultMat = new[] { temp.GetComponent<Renderer>().sharedMaterial };
|
||||
DestroyImmediate(temp);
|
||||
|
||||
foreach (var rend in renderers)
|
||||
{
|
||||
rend.sharedMaterials = defaultMat;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (gltfScene) DestroyImmediate(gltfScene);
|
||||
throw;
|
||||
}
|
||||
|
||||
#if UNITY_2017_3_OR_NEWER
|
||||
if (!_useSceneNameIdentifier)
|
||||
{
|
||||
// Set main asset
|
||||
_mainAssetIdentifier = "main asset";
|
||||
ctx.AddObjectToAsset(_mainAssetIdentifier, gltfScene);
|
||||
}
|
||||
else
|
||||
{
|
||||
// This will be a breaking change, but would be aligned to the import naming from glTFast - allows switching back and forth between importers.
|
||||
_mainAssetIdentifier = $"scenes/{gltfScene.name}";
|
||||
ctx.AddObjectToAsset(_mainAssetIdentifier, gltfScene);
|
||||
}
|
||||
|
||||
// Add meshes
|
||||
foreach (var mesh in meshes)
|
||||
{
|
||||
try
|
||||
{
|
||||
ctx.AddObjectToAsset(GetUniqueName("mesh-" + mesh.name), mesh);
|
||||
} catch(System.InvalidOperationException e) {
|
||||
Debug.LogWarning(e.ToString(), mesh);
|
||||
}
|
||||
}
|
||||
|
||||
#if UNITY_2020_2_OR_NEWER
|
||||
ctx.DependsOnCustomDependency(ColorSpaceDependency);
|
||||
#endif
|
||||
ctx.SetMainObject(gltfScene);
|
||||
#else
|
||||
// Set main asset
|
||||
ctx.SetMainAsset("main asset", gltfScene);
|
||||
|
||||
// Add meshes
|
||||
foreach (var mesh in meshes)
|
||||
{
|
||||
try {
|
||||
ctx.AddSubAsset("mesh " + mesh.name, mesh);
|
||||
} catch (System.InvalidOperationException e) {
|
||||
Debug.LogWarning(e.ToString(), mesh);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private const string ColorSpaceDependency = nameof(GLTFImporter) + "_" + nameof(PlayerSettings.colorSpace);
|
||||
|
||||
#if UNITY_2020_2_OR_NEWER
|
||||
[InitializeOnLoadMethod]
|
||||
private static void UpdateColorSpace()
|
||||
{
|
||||
AssetDatabase.RegisterCustomDependency(ColorSpaceDependency, Hash128.Compute((int) PlayerSettings.colorSpace));
|
||||
}
|
||||
#endif
|
||||
|
||||
private void CreateGLTFScene(string projectFilePath, out GameObject scene, out AnimationClip[] animationClips)
|
||||
{
|
||||
var importOptions = new ImportOptions
|
||||
{
|
||||
DataLoader = new FileLoader(Path.GetDirectoryName(projectFilePath)),
|
||||
AnimationMethod = _importAnimations,
|
||||
AnimationLoopTime = _animationLoopTime,
|
||||
AnimationLoopPose = _animationLoopPose,
|
||||
};
|
||||
using (var stream = File.OpenRead(projectFilePath))
|
||||
{
|
||||
GLTFRoot gLTFRoot;
|
||||
GLTFParser.ParseJson(stream, out gLTFRoot);
|
||||
stream.Position = 0; // Make sure the read position is changed back to the beginning of the file
|
||||
var loader = new GLTFSceneImporter(gLTFRoot, stream, importOptions);
|
||||
loader.MaximumLod = _maximumLod;
|
||||
loader.IsMultithreaded = true;
|
||||
|
||||
loader.LoadSceneAsync().Wait();
|
||||
|
||||
if (gLTFRoot.ExtensionsUsed != null)
|
||||
{
|
||||
_extensions = gLTFRoot.ExtensionsUsed
|
||||
.Select(x => new ExtensionInfo()
|
||||
{
|
||||
name = x,
|
||||
supported = true,
|
||||
used = true,
|
||||
required = gLTFRoot.ExtensionsRequired?.Contains(x) ?? false,
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
_extensions = new List<ExtensionInfo>();
|
||||
}
|
||||
|
||||
_textures = loader.TextureCache
|
||||
.Where(x => x != null)
|
||||
.Select(x => new TextureInfo() { texture = x.Texture, shouldBeLinear = x.IsLinear })
|
||||
.ToList();
|
||||
|
||||
scene = loader.LastLoadedScene;
|
||||
animationClips = loader.CreatedAnimationClips;
|
||||
}
|
||||
}
|
||||
|
||||
private void CopyOrNew<T>(T asset, string assetPath, Action<T> replaceReferences) where T : Object
|
||||
{
|
||||
var existingAsset = AssetDatabase.LoadAssetAtPath<T>(assetPath);
|
||||
if (existingAsset)
|
||||
{
|
||||
EditorUtility.CopySerialized(asset, existingAsset);
|
||||
replaceReferences(existingAsset);
|
||||
return;
|
||||
}
|
||||
|
||||
AssetDatabase.CreateAsset(asset, assetPath);
|
||||
}
|
||||
|
||||
private class TexMaterialMap
|
||||
{
|
||||
public UnityEngine.Material Material { get; set; }
|
||||
public string Property { get; set; }
|
||||
public bool IsNormalMap { get; set; }
|
||||
|
||||
public TexMaterialMap(UnityEngine.Material material, string property, bool isNormalMap)
|
||||
{
|
||||
Material = material;
|
||||
Property = property;
|
||||
IsNormalMap = isNormalMap;
|
||||
}
|
||||
}
|
||||
|
||||
public override bool SupportsRemappedAssetType(Type type)
|
||||
{
|
||||
if (type == typeof(Material))
|
||||
return true;
|
||||
return base.SupportsRemappedAssetType(type);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 804e1ce4c496647cfa3f1a1134187c71
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,334 @@
|
||||
#if UNITY_2017_1_OR_NEWER
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEditor;
|
||||
|
||||
using UnityEngine;
|
||||
#if UNITY_2020_2_OR_NEWER
|
||||
using UnityEditor.AssetImporters;
|
||||
#else
|
||||
using UnityEditor.Experimental.AssetImporters;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
[CustomEditor(typeof(GLTFImporter))]
|
||||
[CanEditMultipleObjects]
|
||||
internal class GLTFImporterInspector : UnityGLTFTabbedEditor
|
||||
{
|
||||
private string[] _importNormalsNames;
|
||||
|
||||
public override void OnEnable()
|
||||
{
|
||||
AddTab(new GltfAssetImporterTab(this, "Model", ModelInspectorGUI));
|
||||
AddTab(new GltfAssetImporterTab(this, "Animation", AnimationInspectorGUI));
|
||||
AddTab(new GltfAssetImporterTab(this, "Materials", MaterialInspectorGUI));
|
||||
AddTab(new GltfAssetImporterTab(this, "Extensions", ExtensionInspectorGUI));
|
||||
|
||||
base.OnEnable();
|
||||
}
|
||||
|
||||
private void TextureWarningsGUI(GLTFImporter t)
|
||||
{
|
||||
if (!t) return;
|
||||
if (!TextureImportSettingsAreCorrect(t))
|
||||
{
|
||||
EditorGUILayout.HelpBox("Some Textures have incorrect linear/sRGB settings. Results might be incorrect.", MessageType.Warning);
|
||||
if (GUILayout.Button("Fix All"))
|
||||
{
|
||||
FixTextureImportSettings(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ModelInspectorGUI()
|
||||
{
|
||||
var t = target as GLTFImporter;
|
||||
if (!t) EditorGUILayout.LabelField("NOOOO");
|
||||
|
||||
if (!t) return;
|
||||
|
||||
// serializedObject.Update();
|
||||
if (_importNormalsNames == null)
|
||||
{
|
||||
_importNormalsNames = Enum.GetNames(typeof(GLTFImporterNormals))
|
||||
.Select(n => ObjectNames.NicifyVariableName(n))
|
||||
.ToArray();
|
||||
}
|
||||
EditorGUILayout.LabelField("Scene", EditorStyles.boldLabel);
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._removeEmptyRootObjects)));
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._scaleFactor)));
|
||||
// EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._maximumLod)), new GUIContent("Maximum Shader LOD"));
|
||||
EditorGUILayout.Separator();
|
||||
EditorGUILayout.LabelField("Meshes", EditorStyles.boldLabel);
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._readWriteEnabled)), new GUIContent("Read/Write"));
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._generateColliders)));
|
||||
EditorGUILayout.Separator();
|
||||
EditorGUILayout.LabelField("Geometry", EditorStyles.boldLabel);
|
||||
EditorGUI.BeginChangeCheck();
|
||||
var importNormalsProp = serializedObject.FindProperty(nameof(GLTFImporter._importNormals));
|
||||
var importNormals = EditorGUILayout.Popup("Normals", importNormalsProp.intValue, _importNormalsNames);
|
||||
if (EditorGUI.EndChangeCheck())
|
||||
{
|
||||
importNormalsProp.intValue = importNormals;
|
||||
}
|
||||
EditorGUI.BeginChangeCheck();
|
||||
var importTangentsProp = serializedObject.FindProperty(nameof(GLTFImporter._importTangents));
|
||||
var importTangents = EditorGUILayout.Popup("Tangents", importTangentsProp.intValue, _importNormalsNames);
|
||||
if (EditorGUI.EndChangeCheck())
|
||||
{
|
||||
importTangentsProp.intValue = importTangents;
|
||||
}
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._swapUvs)), new GUIContent("Swap UVs"));
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._generateLightmapUVs)), new GUIContent("Generate Lightmap UVs"));
|
||||
EditorGUILayout.Separator();
|
||||
|
||||
TextureWarningsGUI(t);
|
||||
}
|
||||
|
||||
private void AnimationInspectorGUI()
|
||||
{
|
||||
var t = target as GLTFImporter;
|
||||
if (!t) return;
|
||||
|
||||
var anim = serializedObject.FindProperty(nameof(GLTFImporter._importAnimations));
|
||||
EditorGUILayout.PropertyField(anim, new GUIContent("Animation Type"));
|
||||
if (anim.enumValueIndex > 0)
|
||||
{
|
||||
var loopTime = serializedObject.FindProperty(nameof(GLTFImporter._animationLoopTime));
|
||||
EditorGUILayout.PropertyField(loopTime, new GUIContent("Loop Time"));
|
||||
if (loopTime.boolValue)
|
||||
{
|
||||
EditorGUI.indentLevel++;
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._animationLoopPose)), new GUIContent("Loop Pose"));
|
||||
EditorGUI.indentLevel--;
|
||||
}
|
||||
}
|
||||
|
||||
// warn if Humanoid rig import has failed
|
||||
if (!HasModified() && anim.enumValueIndex == (int) AnimationMethod.MecanimHumanoid && !AssetDatabase.LoadAssetAtPath<Avatar>(t.assetPath))
|
||||
{
|
||||
EditorGUILayout.Separator();
|
||||
EditorGUILayout.HelpBox("The model doesn't contain a valid Humanoid rig. See the console for more information.", MessageType.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void MaterialInspectorGUI()
|
||||
{
|
||||
var t = target as GLTFImporter;
|
||||
if (!t) return;
|
||||
|
||||
var mats = serializedObject.FindProperty("m_Materials");
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._importMaterials)));
|
||||
EditorGUILayout.Separator();
|
||||
|
||||
// extract and remap materials
|
||||
if (mats != null && mats.serializedObject != null)
|
||||
{
|
||||
EditorGUI.indentLevel++;
|
||||
var externalObjectMap = t.GetExternalObjectMap();
|
||||
|
||||
void ExtractMaterial(Material subAsset, bool importImmediately)
|
||||
{
|
||||
if (!subAsset) return;
|
||||
var filename = SanitizePath(subAsset.name);
|
||||
var dirName = Path.GetDirectoryName(t.assetPath) + "/Materials";
|
||||
if (!Directory.Exists(dirName))
|
||||
Directory.CreateDirectory(dirName);
|
||||
var destinationPath = dirName + "/" + filename + ".mat";
|
||||
var assetPath = AssetDatabase.GetAssetPath(subAsset);
|
||||
|
||||
var clone = Instantiate(subAsset);
|
||||
AssetDatabase.CreateAsset(clone, destinationPath);
|
||||
|
||||
var assetImporter = AssetImporter.GetAtPath(assetPath);
|
||||
assetImporter.AddRemap(new AssetImporter.SourceAssetIdentifier(subAsset), clone);
|
||||
|
||||
if (importImmediately)
|
||||
{
|
||||
AssetDatabase.WriteImportSettingsIfDirty(assetPath);
|
||||
AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
|
||||
}
|
||||
}
|
||||
|
||||
const string key2 = nameof(GLTFImporterInspector) + "_RemapMaterials_List";
|
||||
var newVal2 = EditorGUILayout.BeginFoldoutHeaderGroup(SessionState.GetBool(key2, false), "Remap Materials (" + mats.arraySize + ")");
|
||||
SessionState.SetBool(key2, newVal2);
|
||||
if (newVal2)
|
||||
{
|
||||
for (var i = 0; i < mats.arraySize; i++)
|
||||
{
|
||||
var mat = mats.GetArrayElementAtIndex(i).objectReferenceValue as Material;
|
||||
if (!mat) continue;
|
||||
var id = new AssetImporter.SourceAssetIdentifier(mat);
|
||||
externalObjectMap.TryGetValue(id, out var remap);
|
||||
EditorGUILayout.BeginHorizontal();
|
||||
// EditorGUILayout.ObjectField(/*mat.name,*/ mat, typeof(Material), false);
|
||||
EditorGUI.BeginChangeCheck();
|
||||
var newObj = EditorGUILayout.ObjectField(mat.name, remap, typeof(Material), false);
|
||||
if (EditorGUI.EndChangeCheck())
|
||||
{
|
||||
if (newObj && newObj != mat)
|
||||
t.AddRemap(id, newObj);
|
||||
else
|
||||
t.RemoveRemap(id);
|
||||
}
|
||||
|
||||
if (!remap)
|
||||
{
|
||||
if (GUILayout.Button("Extract", GUILayout.Width(60)))
|
||||
{
|
||||
ExtractMaterial(mat, true);
|
||||
GUIUtility.ExitGUI();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (GUILayout.Button("Restore", GUILayout.Width(60)))
|
||||
{
|
||||
t.RemoveRemap(id);
|
||||
#if UNITY_2022_2_OR_NEWER
|
||||
SaveChanges();
|
||||
#else
|
||||
ApplyAndImport();
|
||||
#endif
|
||||
GUIUtility.ExitGUI();
|
||||
}
|
||||
}
|
||||
|
||||
EditorGUILayout.EndHorizontal();
|
||||
}
|
||||
}
|
||||
|
||||
EditorGUILayout.BeginHorizontal();
|
||||
EditorGUILayout.PrefixLabel(" ");
|
||||
if (GUILayout.Button("Restore Materials"))
|
||||
{
|
||||
for (var i = 0; i < mats.arraySize; i++)
|
||||
{
|
||||
var mat = mats.GetArrayElementAtIndex(i).objectReferenceValue as Material;
|
||||
if (!mat) continue;
|
||||
t.RemoveRemap(new AssetImporter.SourceAssetIdentifier(mat));
|
||||
}
|
||||
}
|
||||
|
||||
if (GUILayout.Button("Extract Materials"))
|
||||
{
|
||||
for (var i = 0; i < mats.arraySize; i++)
|
||||
{
|
||||
AssetDatabase.StartAssetEditing();
|
||||
ExtractMaterial(mats.GetArrayElementAtIndex(i).objectReferenceValue as Material, false);
|
||||
AssetDatabase.StopAssetEditing();
|
||||
var assetPath = AssetDatabase.GetAssetPath(target);
|
||||
AssetDatabase.WriteImportSettingsIfDirty(assetPath);
|
||||
AssetDatabase.Refresh();
|
||||
}
|
||||
}
|
||||
|
||||
EditorGUILayout.EndHorizontal();
|
||||
EditorGUI.indentLevel--;
|
||||
}
|
||||
|
||||
EditorGUILayout.EndFoldoutHeaderGroup();
|
||||
|
||||
EditorGUILayout.Separator();
|
||||
|
||||
var identifierProp = serializedObject.FindProperty(nameof(GLTFImporter._useSceneNameIdentifier));
|
||||
if (!identifierProp.boolValue)
|
||||
{
|
||||
EditorGUILayout.HelpBox("This asset uses the old main asset identifier. Upgrade to the new one if you want to seamlessly switch between glTFast and UnityGLTF on import.\nNOTE: This will break existing scene references.", MessageType.Info);
|
||||
if (GUILayout.Button("Update Asset Identifier"))
|
||||
{
|
||||
identifierProp.boolValue = true;
|
||||
serializedObject.ApplyModifiedProperties();
|
||||
try
|
||||
{
|
||||
#if UNITY_2022_2_OR_NEWER
|
||||
SaveChanges();
|
||||
#else
|
||||
ApplyAndImport();
|
||||
#endif
|
||||
GUIUtility.ExitGUI();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignore - seems in some cases the GameObjectInspector will throw
|
||||
}
|
||||
}
|
||||
}
|
||||
// EditorGUILayout.PropertyField(serializedObject.FindProperty("_useJpgTextures"), new GUIContent("Use JPG Textures"));
|
||||
|
||||
EditorGUILayout.Separator();
|
||||
|
||||
TextureWarningsGUI(t);
|
||||
}
|
||||
|
||||
private void ExtensionInspectorGUI()
|
||||
{
|
||||
var t = target as GLTFImporter;
|
||||
if (!t) return;
|
||||
|
||||
EditorGUI.BeginDisabledGroup(true);
|
||||
var mainAssetIdentifierProp = serializedObject.FindProperty(nameof(GLTFImporter._mainAssetIdentifier));
|
||||
EditorGUILayout.PropertyField(mainAssetIdentifierProp);
|
||||
|
||||
EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(GLTFImporter._extensions)), new GUIContent("Extensions"));
|
||||
EditorGUI.EndDisabledGroup();
|
||||
}
|
||||
|
||||
public static bool TextureImportSettingsAreCorrect(GLTFImporter importer)
|
||||
{
|
||||
return importer.Textures.All(x =>
|
||||
{
|
||||
if (AssetDatabase.Contains(x.texture) && AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(x.texture)) is TextureImporter textureImporter)
|
||||
{
|
||||
return textureImporter.sRGBTexture == !x.shouldBeLinear;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public static void FixTextureImportSettings(GLTFImporter importer)
|
||||
{
|
||||
var haveStartedAssetEditing = false;
|
||||
foreach (var x in importer.Textures)
|
||||
{
|
||||
if (!AssetDatabase.Contains(x.texture) || !(AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(x.texture)) is TextureImporter textureImporter)) continue;
|
||||
|
||||
// skip if already correct
|
||||
if (textureImporter.sRGBTexture == !x.shouldBeLinear)
|
||||
continue;
|
||||
|
||||
if (!haveStartedAssetEditing)
|
||||
{
|
||||
haveStartedAssetEditing = true;
|
||||
AssetDatabase.StartAssetEditing();
|
||||
}
|
||||
|
||||
textureImporter.sRGBTexture = !x.shouldBeLinear;
|
||||
textureImporter.SaveAndReimport();
|
||||
}
|
||||
|
||||
if (haveStartedAssetEditing)
|
||||
AssetDatabase.StopAssetEditing();
|
||||
}
|
||||
|
||||
private static string SanitizePath(string subAssetName)
|
||||
{
|
||||
// make filename safe without using Regex
|
||||
var invalidChars = Path.GetInvalidFileNameChars();
|
||||
var sb = new StringBuilder(subAssetName);
|
||||
for (int i = 0; i < sb.Length; i++)
|
||||
{
|
||||
if (invalidChars.Contains(sb[i]))
|
||||
{
|
||||
sb[i] = '_';
|
||||
}
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 20d4d64afd8e74d39a8d8fad13d909fc
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,11 @@
|
||||
#if UNITY_2017_1_OR_NEWER
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public enum GLTFImporterNormals
|
||||
{
|
||||
Import,
|
||||
Calculate,
|
||||
None
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f3961a7b54dd64330a1228d3aa9993c0
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 043bcd2f8cd689d4298a4ff9f11d1056
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,219 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
internal class AvatarUtils
|
||||
{
|
||||
// A static dictionary containing the mapping from joint/bones names in the model
|
||||
// to the names Unity uses for them internally.
|
||||
// In this case they match the naming from the included Mixamo model on the left
|
||||
// and the Unity equivalent name on the right.
|
||||
// This does not need to be hard-coded.
|
||||
public static Dictionary<string, string> HumanSkeletonNames = new Dictionary<string, string>()
|
||||
{
|
||||
{"mixamorig:Spine1", "Chest"},
|
||||
{"mixamorig:Head", "Head" },
|
||||
{"mixamorig:Hips", "Hips" },
|
||||
{"mixamorig:LeftHandIndex3", "Left Index Distal" },
|
||||
{"mixamorig:LeftHandIndex2", "Left Index Intermediate" },
|
||||
{"mixamorig:LeftHandIndex1", "Left Index Proximal" },
|
||||
{"mixamorig:LeftHandPinky3", "Left Little Distal" },
|
||||
{"mixamorig:LeftHandPinky2", "Left Little Intermediate" },
|
||||
{"mixamorig:LeftHandPinky1", "Left Little Proximal" },
|
||||
{"mixamorig:LeftHandMiddle3", "Left Middle Distal" },
|
||||
{"mixamorig:LeftHandMiddle2", "Left Middle Intermediate" },
|
||||
{"mixamorig:LeftHandMiddle1", "Left Middle Proximal" },
|
||||
{"mixamorig:LeftHandRing3", "Left Ring Distal" },
|
||||
{"mixamorig:LeftHandRing2", "Left Ring Intermediate" },
|
||||
{"mixamorig:LeftHandRing1", "Left Ring Proximal" },
|
||||
{"mixamorig:LeftHandThumb3", "Left Thumb Distal" },
|
||||
{"mixamorig:LeftHandThumb2", "Left Thumb Intermediate" },
|
||||
{"mixamorig:LeftHandThumb1", "Left Thumb Proximal" },
|
||||
{"mixamorig:LeftFoot", "LeftFoot" },
|
||||
{"mixamorig:LeftHand", "LeftHand" },
|
||||
{"mixamorig:LeftForeArm", "LeftLowerArm" },
|
||||
{"mixamorig:LeftLeg", "LeftLowerLeg" },
|
||||
{"mixamorig:LeftShoulder", "LeftShoulder" },
|
||||
{"mixamorig:LeftToeBase", "LeftToes" },
|
||||
{"mixamorig:LeftArm", "LeftUpperArm" },
|
||||
{"mixamorig:LeftUpLeg", "LeftUpperLeg" },
|
||||
{"mixamorig:Neck", "Neck" },
|
||||
{"mixamorig:RightHandIndex3", "Right Index Distal" },
|
||||
{"mixamorig:RightHandIndex2", "Right Index Intermediate" },
|
||||
{"mixamorig:RightHandIndex1", "Right Index Proximal" },
|
||||
{"mixamorig:RightHandPinky3", "Right Little Distal" },
|
||||
{"mixamorig:RightHandPinky2", "Right Little Intermediate" },
|
||||
{"mixamorig:RightHandPinky1", "Right Little Proximal" },
|
||||
{"mixamorig:RightHandMiddle3", "Right Middle Distal" },
|
||||
{"mixamorig:RightHandMiddle2", "Right Middle Intermediate" },
|
||||
{"mixamorig:RightHandMiddle1", "Right Middle Proximal" },
|
||||
{"mixamorig:RightHandRing3", "Right Ring Distal" },
|
||||
{"mixamorig:RightHandRing2", "Right Ring Intermediate" },
|
||||
{"mixamorig:RightHandRing1", "Right Ring Proximal" },
|
||||
{"mixamorig:RightHandThumb3", "Right Thumb Distal" },
|
||||
{"mixamorig:RightHandThumb2", "Right Thumb Intermediate" },
|
||||
{"mixamorig:RightHandThumb1", "Right Thumb Proximal" },
|
||||
{"mixamorig:RightFoot", "RightFoot" },
|
||||
{"mixamorig:RightHand", "RightHand" },
|
||||
{"mixamorig:RightForeArm", "RightLowerArm" },
|
||||
{"mixamorig:RightLeg", "RightLowerLeg" },
|
||||
{"mixamorig:RightShoulder", "RightShoulder" },
|
||||
{"mixamorig:RightToeBase", "RightToes" },
|
||||
{"mixamorig:RightArm", "RightUpperArm" },
|
||||
{"mixamorig:RightUpLeg", "RightUpperLeg" },
|
||||
{"mixamorig:Spine", "Spine" },
|
||||
{"mixamorig:Spine2", "UpperChest" },
|
||||
|
||||
// Other common Avatar formats can also be added here
|
||||
// { "root", "" },
|
||||
{ "hips", "Hips" },
|
||||
{ "spine", "Spine" },
|
||||
{ "chest", "Chest" },
|
||||
{ "upperChest", "UpperChest" },
|
||||
{ "neck", "Neck" },
|
||||
{ "head", "Head" },
|
||||
{ "leftEye", "LeftEye" },
|
||||
// { "eyeL_end", "" },
|
||||
{ "rightEye", "RightEye" },
|
||||
// { "eyeR_end", "" },
|
||||
{ "leftShoulder", "LeftShoulder" },
|
||||
{ "leftUpperArm", "LeftUpperArm" },
|
||||
{ "leftLowerArm", "LeftLowerArm" },
|
||||
{ "leftHand", "LeftHand" },
|
||||
// { "leftThumbMetacarpal", "" },
|
||||
// { "leftThumbProximal", "" },
|
||||
// { "leftThumbDistal", "" },
|
||||
// { "thumbdistalL_end", "" },
|
||||
// { "leftIndexProximal", "" },
|
||||
// { "leftIndexIntermediate", "" },
|
||||
// { "leftIndexDistal", "" },
|
||||
// { "indexdistalL_end", "" },
|
||||
// { "leftMiddleProximal", "" },
|
||||
// { "leftMiddleIntermediate", "" },
|
||||
// { "leftMiddleDistal", "" },
|
||||
// { "middledistalL_end", "" },
|
||||
// { "leftRingProximal", "" },
|
||||
// { "leftRingIntermediate", "" },
|
||||
// { "leftRingDistal", "" },
|
||||
// { "ringdistalL_end", "" },
|
||||
// { "leftLittleProximal", "" },
|
||||
// { "leftLittleIntermediate", "" },
|
||||
// { "leftLittleDistal", "" },
|
||||
// { "littledistalL_end", "" },
|
||||
{ "rightShoulder", "RightShoulder" },
|
||||
{ "rightUpperArm", "RightUpperArm" },
|
||||
{ "rightLowerArm", "RightLowerArm" },
|
||||
{ "rightHand", "RightHand" },
|
||||
// { "rightThumbMetacarpal", "" },
|
||||
// { "rightThumbProximal", "" },
|
||||
// { "rightThumbDistal", "" },
|
||||
// { "thumbdistalR_end", "" },
|
||||
// { "rightIndexProximal", "" },
|
||||
// { "rightIndexIntermediate", "" },
|
||||
// { "rightIndexDistal", "" },
|
||||
// { "indexdistalR_end", "" },
|
||||
// { "rightMiddleProximal", "" },
|
||||
// { "rightMiddleIntermediate", "" },
|
||||
// { "rightMiddleDistal", "" },
|
||||
// { "middledistalR_end", "" },
|
||||
// { "rightRingProximal", "" },
|
||||
// { "rightRingIntermediate", "" },
|
||||
// { "rightRingDistal", "" },
|
||||
// { "ringdistalR_end", "" },
|
||||
// { "rightLittleProximal", "" },
|
||||
// { "rightLittleIntermediate", "" },
|
||||
// { "rightLittleDistal", "" },
|
||||
// { "littledistalR_end", "" },
|
||||
{ "leftUpperLeg", "LeftUpperLeg" },
|
||||
{ "leftLowerLeg", "LeftLowerLeg" },
|
||||
{ "leftFoot", "LeftFoot" },
|
||||
{ "leftToes", "LeftToes" },
|
||||
// { "toesL_end", "" },
|
||||
{ "rightUpperLeg", "RightUpperLeg" },
|
||||
{ "rightLowerLeg", "RightLowerLeg" },
|
||||
{ "rightFoot", "RightFoot" },
|
||||
{ "rightToes", "RightToes" },
|
||||
// { "toesR_end", "" },
|
||||
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Create a HumanDescription out of an avatar GameObject.
|
||||
/// The HumanDescription is what is needed to create an Avatar object
|
||||
/// using the AvatarBuilder API. This function takes care of
|
||||
/// creating the HumanDescription by going through the avatar's
|
||||
/// hierarchy, defining its T-Pose in the skeleton, and defining
|
||||
/// the transform/bone mapping in the HumanBone array.
|
||||
/// </summary>
|
||||
/// <param name="avatarRoot">Root of your avatar object</param>
|
||||
/// <returns>A HumanDescription which can be fed to the AvatarBuilder API</returns>
|
||||
public static HumanDescription CreateHumanDescription(GameObject avatarRoot)
|
||||
{
|
||||
HumanDescription description = new HumanDescription()
|
||||
{
|
||||
armStretch = 0.05f,
|
||||
feetSpacing = 0f,
|
||||
hasTranslationDoF = false,
|
||||
legStretch = 0.05f,
|
||||
lowerArmTwist = 0.5f,
|
||||
lowerLegTwist = 0.5f,
|
||||
upperArmTwist = 0.5f,
|
||||
upperLegTwist = 0.5f,
|
||||
skeleton = CreateSkeleton(avatarRoot),
|
||||
human = CreateHuman(avatarRoot),
|
||||
};
|
||||
return description;
|
||||
}
|
||||
|
||||
//Create a SkeletonBone array out of an Avatar GameObject
|
||||
//This assumes that the Avatar as supplied is in a T-Pose
|
||||
//The local positions of its bones/joints are used to define this T-Pose
|
||||
private static SkeletonBone[] CreateSkeleton(GameObject avatarRoot)
|
||||
{
|
||||
List<SkeletonBone> skeleton = new List<SkeletonBone>();
|
||||
|
||||
Transform[] avatarTransforms = avatarRoot.GetComponentsInChildren<Transform>();
|
||||
foreach (Transform avatarTransform in avatarTransforms)
|
||||
{
|
||||
SkeletonBone bone = new SkeletonBone()
|
||||
{
|
||||
name = avatarTransform.name,
|
||||
position = avatarTransform.localPosition,
|
||||
rotation = avatarTransform.localRotation,
|
||||
scale = avatarTransform.localScale
|
||||
};
|
||||
|
||||
skeleton.Add(bone);
|
||||
}
|
||||
return skeleton.ToArray();
|
||||
}
|
||||
|
||||
//Create a HumanBone array out of an Avatar GameObject
|
||||
//This is where the various bones/joints get associated with the
|
||||
//joint names that Unity understands. This is done using the
|
||||
//static dictionary defined at the top.
|
||||
private static HumanBone[] CreateHuman(GameObject avatarRoot)
|
||||
{
|
||||
List<HumanBone> human = new List<HumanBone>();
|
||||
|
||||
Transform[] avatarTransforms = avatarRoot.GetComponentsInChildren<Transform>();
|
||||
foreach (Transform avatarTransform in avatarTransforms)
|
||||
{
|
||||
if (HumanSkeletonNames.TryGetValue(avatarTransform.name, out string humanName))
|
||||
{
|
||||
HumanBone bone = new HumanBone
|
||||
{
|
||||
boneName = avatarTransform.name,
|
||||
humanName = humanName,
|
||||
limit = new HumanLimit()
|
||||
};
|
||||
bone.limit.useDefaultValues = true;
|
||||
|
||||
human.Add(bone);
|
||||
}
|
||||
}
|
||||
return human.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 15daddec8a84e584db94b127e7bd05b7
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,271 @@
|
||||
#if !NO_INTERNALS_ACCESS
|
||||
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
|
||||
#if UNITY_EDITOR
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using UnityEditor;
|
||||
using UnityEditorInternal;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public static class GLTFMaterialHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Return false if other delegates should take over. Only return true if you did work and assigned material.shader = newShader.
|
||||
/// </summary>
|
||||
public delegate bool ConvertMaterialToGLTFDelegate(Material material, Shader oldShader, Shader newShader);
|
||||
private static event ConvertMaterialToGLTFDelegate ConvertMaterialDelegates;
|
||||
|
||||
public static void RegisterMaterialConversionToGLTF(ConvertMaterialToGLTFDelegate converter) => ConvertMaterialDelegates += converter;
|
||||
public static void UnregisterMaterialConversionToGLTF(ConvertMaterialToGLTFDelegate converter) => ConvertMaterialDelegates -= converter;
|
||||
|
||||
public static void ConvertMaterialToGLTF(Material material, Shader oldShader, Shader newShader)
|
||||
{
|
||||
if (ConvertMaterialDelegates != null)
|
||||
{
|
||||
var list = ConvertMaterialDelegates.GetInvocationList();
|
||||
foreach (var entry in list)
|
||||
{
|
||||
var cb = (ConvertMaterialToGLTFDelegate) entry;
|
||||
if (cb != null && cb.Invoke(material, oldShader, newShader))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// IDEA ideally this would use the same code path as material export/import - would reduce the amount of code duplication considerably.
|
||||
// E.g. calling something like
|
||||
// var glTFMaterial = ExportMaterial(material);
|
||||
// ImportAndOverrideMaterial(material, glTFMaterial);
|
||||
// that uses all the same heuristics, texture conversions, ...
|
||||
|
||||
var msg = "No automatic conversion\nfrom " + oldShader.name + "\nto " + newShader.name + "\nfound.\n\nYou can create a conversion script, adjust which old properties map to which new properties, and switch the shader again.";
|
||||
|
||||
#if UNITY_EDITOR
|
||||
var choice = EditorUtility.DisplayDialogComplex("Shader Conversion", msg, "Just set shader", "Cancel", "Create and open conversion script");
|
||||
switch (choice)
|
||||
{
|
||||
case 0: // OK
|
||||
material.shader = newShader;
|
||||
break;
|
||||
case 1: // Cancel
|
||||
break;
|
||||
case 2: // Alt
|
||||
var path = ShaderConversion.CreateConversionScript(oldShader, newShader);
|
||||
InternalEditorUtility.OpenFileAtLineExternal(path, 0);
|
||||
break;
|
||||
}
|
||||
#else
|
||||
Debug.Log(msg + " Make sure your material properties match the new shader. You can add your own conversion callbacks via `RegisterMaterialConversionToGLTF`. If you think this should have been converted automatically: please open a feature request!");
|
||||
material.shader = newShader;
|
||||
#endif
|
||||
}
|
||||
|
||||
public static void ValidateMaterialKeywords(Material material)
|
||||
{
|
||||
// TODO ensure we're setting correct keywords for
|
||||
// - existence of a normal map
|
||||
// - existence of emission color values or texture
|
||||
// -
|
||||
|
||||
// var needsVolumeTransmission = false;
|
||||
// needsVolumeTransmission |= material.HasProperty(thicknessFactor) && material.GetFloat(thicknessFactor) > 0;
|
||||
// needsVolumeTransmission |= material.HasProperty(transmissionFactor) && material.GetFloat(transmissionFactor) > 0;
|
||||
// material.SetKeyword("_VOLUME_TRANSMISSION", needsVolumeTransmission);
|
||||
//
|
||||
// var needsIridescence = material.HasProperty(iridescenceFactor) && material.GetFloat(iridescenceFactor) > 0;
|
||||
// material.SetKeyword("_IRIDESCENCE", needsIridescence);
|
||||
//
|
||||
// var needsSpecular = material.HasProperty(specularFactor) && material.GetFloat(specularFactor) > 0;
|
||||
// material.SetKeyword("_SPECULAR", needsSpecular);
|
||||
|
||||
if (material.IsKeywordEnabled("_VOLUME_TRANSMISSION_ON"))
|
||||
{
|
||||
// // approximation when transmission is on but roughness == 0
|
||||
// // (no opaque pass required)
|
||||
// TODO does weird things with transparency but still rendering into the Opaque Texture for some reason
|
||||
// if (material.HasProperty("roughnessFactor") && material.GetFloat("roughnessFactor") == 0)
|
||||
// {
|
||||
// // enforce transparent
|
||||
// if (material.HasProperty("_QueueControl")) material.SetFloat("_QueueControl", 0);
|
||||
// if (material.HasProperty("_BUILTIN_QueueControl")) material.SetFloat("_BUILTIN_QueueControl", 0);
|
||||
// if (material.HasProperty("_BUILTIN_Surface")) material.SetFloat("_BUILTIN_Surface", 1);
|
||||
// if (material.HasProperty("_Surface")) material.SetFloat("_Surface", 1);
|
||||
// material.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
|
||||
// material.EnableKeyword("_BUILTIN_SURFACE_TYPE_TRANSPARENT");
|
||||
// material.renderQueue = -1;
|
||||
// }
|
||||
// else
|
||||
{
|
||||
// enforce Opaque
|
||||
if (material.HasProperty("_BUILTIN_Surface")) material.SetFloat("_BUILTIN_Surface", 0);
|
||||
if (material.HasProperty("_Surface")) material.SetFloat("_Surface", 0);
|
||||
material.DisableKeyword("_SURFACE_TYPE_TRANSPARENT");
|
||||
material.DisableKeyword("_BUILTIN_SURFACE_TYPE_TRANSPARENT");
|
||||
|
||||
// enforce queue control and render queue 3000
|
||||
if (material.HasProperty("_QueueControl")) material.SetFloat("_QueueControl", 1);
|
||||
if (material.HasProperty("_BUILTIN_QueueControl")) material.SetFloat("_BUILTIN_QueueControl", 1);
|
||||
|
||||
// not a great choice: using 2999 as magic value for "we automatically set the queue for you"
|
||||
// so the change can be reverted if someone toggles transmission on and then off again.
|
||||
material.renderQueue = 2999;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (material.renderQueue == 2999)
|
||||
{
|
||||
if (material.HasProperty("_QueueControl")) material.SetFloat("_QueueControl", 0);
|
||||
if (material.HasProperty("_BUILTIN_QueueControl")) material.SetFloat("_BUILTIN_QueueControl", 0);
|
||||
material.renderQueue = -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (material.HasProperty("emissiveFactor"))
|
||||
material.globalIlluminationFlags = MaterialEditor.FixupEmissiveFlag(material.GetColor("emissiveFactor"), material.globalIlluminationFlags);
|
||||
|
||||
if (!material.IsKeywordEnabled("_TEXTURE_TRANSFORM_ON"))
|
||||
{
|
||||
if (material.GetTextureScale("baseColorTexture") != Vector2.one || material.GetTextureOffset("baseColorTexture") != Vector2.zero)
|
||||
{
|
||||
SetKeyword(material, "_TEXTURE_TRANSFORM", true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetKeyword(Material material, string keyword, bool state)
|
||||
{
|
||||
if (state)
|
||||
material.EnableKeyword(keyword + "_ON");
|
||||
else
|
||||
material.DisableKeyword(keyword + "_ON");
|
||||
|
||||
if (material.HasProperty(keyword))
|
||||
material.SetFloat(keyword, state ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
internal static class ShaderConversion
|
||||
{
|
||||
public static string CreateConversionScript(Shader oldShader, Shader newShader)
|
||||
{
|
||||
var classShaderName = oldShader.name
|
||||
.Replace("/", "_")
|
||||
.Replace(" ", "_")
|
||||
.Replace("\\", "_");
|
||||
|
||||
var scriptFile = ShaderConversionScriptTemplate;
|
||||
scriptFile = scriptFile.Replace("<OldShader>", classShaderName);
|
||||
scriptFile = scriptFile.Replace("<OldShaderName>", oldShader.name);
|
||||
|
||||
var sb = new StringBuilder();
|
||||
foreach(var (propName, propDisplayName, type) in GetShaderProperties(oldShader))
|
||||
{
|
||||
sb.AppendLine($"\t\tvar {propName} = material.{MethodFromType("Get", type)}(\"{propName}\"); // {propDisplayName}");
|
||||
}
|
||||
|
||||
var sb2 = new StringBuilder();
|
||||
foreach(var (propName, propDisplayName, type) in GetShaderProperties(newShader))
|
||||
{
|
||||
sb2.AppendLine($"\t\t// material.{MethodFromType("Set", type)}(\"{propName}\", insert_value_here); // {propDisplayName}");
|
||||
}
|
||||
|
||||
scriptFile = scriptFile.Replace("\t\t<OldProperties>", sb.ToString());
|
||||
scriptFile = scriptFile.Replace("\t\t<NewProperties>", sb2.ToString());
|
||||
|
||||
const string dir = "Assets/Editor/ShaderConversions";
|
||||
Directory.CreateDirectory(dir);
|
||||
var fileName = dir + "/" + classShaderName + ".cs";
|
||||
if (!File.Exists(fileName) || EditorUtility.DisplayDialog("File already exists", $"The file \"{fileName}\" already exists. Replace?", "Replace", "Cancel"))
|
||||
File.WriteAllText(fileName, scriptFile);
|
||||
|
||||
AssetDatabase.Refresh();
|
||||
|
||||
return fileName;
|
||||
}
|
||||
|
||||
private static IEnumerable<(string propName, string propDisplayName, ShaderUtil.ShaderPropertyType type)> GetShaderProperties(Shader shader)
|
||||
{
|
||||
var c = ShaderUtil.GetPropertyCount(shader);
|
||||
for (var i = 0; i < c; i++)
|
||||
{
|
||||
if (ShaderUtil.IsShaderPropertyHidden(shader, i)) continue;
|
||||
if (ShaderUtil.IsShaderPropertyNonModifiableTexureProperty(shader, i)) continue;
|
||||
|
||||
var propName = ShaderUtil.GetPropertyName(shader, i);
|
||||
if(propName.StartsWith("unity_")) continue;
|
||||
|
||||
var propDisplayName = ShaderUtil.GetPropertyDescription(shader, i);
|
||||
var type = ShaderUtil.GetPropertyType(shader, i);
|
||||
yield return (propName, propDisplayName, type);
|
||||
}
|
||||
}
|
||||
|
||||
private static string MethodFromType(string prefix, ShaderUtil.ShaderPropertyType propertyType)
|
||||
{
|
||||
switch (propertyType)
|
||||
{
|
||||
case ShaderUtil.ShaderPropertyType.Color: return prefix + "Color";
|
||||
case ShaderUtil.ShaderPropertyType.Float: return prefix + "Float";
|
||||
#if UNITY_2021_1_OR_NEWER
|
||||
case ShaderUtil.ShaderPropertyType.Int: return prefix + "Int";
|
||||
#endif
|
||||
case ShaderUtil.ShaderPropertyType.Range: return prefix + "Float";
|
||||
case ShaderUtil.ShaderPropertyType.Vector: return prefix + "Vector";
|
||||
case ShaderUtil.ShaderPropertyType.TexEnv: return prefix + "Texture";
|
||||
}
|
||||
|
||||
return prefix + "UnknownPropertyType"; // compiler error
|
||||
}
|
||||
|
||||
private const string ShaderConversionScriptTemplate =
|
||||
@"using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityGLTF;
|
||||
|
||||
class Convert_<OldShader>_to_GLTF
|
||||
{
|
||||
const string shaderName = ""<OldShaderName>"";
|
||||
|
||||
[InitializeOnLoadMethod]
|
||||
private static void Register()
|
||||
{
|
||||
GLTFMaterialHelper.RegisterMaterialConversionToGLTF(ConvertMaterialProperties);
|
||||
}
|
||||
|
||||
private static bool ConvertMaterialProperties(Material material, Shader oldShader, Shader newShader)
|
||||
{
|
||||
if (oldShader.name != shaderName) return false;
|
||||
|
||||
// Reading old shader properties.
|
||||
|
||||
<OldProperties>
|
||||
material.shader = newShader;
|
||||
|
||||
// Assigning new shader properties.
|
||||
// Uncomment lines you need, and set properties from values from the section above.
|
||||
|
||||
<NewProperties>
|
||||
|
||||
// Ensure keywords are correctly set after conversion.
|
||||
// Example:
|
||||
// if (material.GetFloat(""_VERTEX_COLORS"") > 0.5f) material.EnableKeyword(""_VERTEX_COLORS_ON"");
|
||||
|
||||
ShaderGraphHelpers.ValidateMaterialKeywords(material);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ad1a4409c80a9004781468cca77d6224
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,102 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
internal static class HumanoidSetup
|
||||
{
|
||||
private static MethodInfo _SetupHumanSkeleton;
|
||||
|
||||
internal static Avatar AddAvatarToGameObject(GameObject gameObject)
|
||||
{
|
||||
HumanDescription description = AvatarUtils.CreateHumanDescription(gameObject);
|
||||
var bones = description.human;
|
||||
SetupHumanSkeleton(gameObject, ref bones, out var skeletonBones, out var hasTranslationDoF);
|
||||
description.human = bones;
|
||||
description.skeleton = skeletonBones;
|
||||
description.hasTranslationDoF = hasTranslationDoF;
|
||||
|
||||
Avatar avatar = AvatarBuilder.BuildHumanAvatar(gameObject, description);
|
||||
avatar.name = "Avatar";
|
||||
|
||||
if (!avatar.isValid)
|
||||
{
|
||||
Object.DestroyImmediate(avatar);
|
||||
return null;
|
||||
}
|
||||
|
||||
var animator = gameObject.GetComponent<Animator>();
|
||||
if (animator) animator.avatar = avatar;
|
||||
return avatar;
|
||||
}
|
||||
|
||||
private static void SetupHumanSkeleton(
|
||||
GameObject modelPrefab,
|
||||
ref HumanBone[] humanBoneMappingArray,
|
||||
out SkeletonBone[] skeletonBones,
|
||||
out bool hasTranslationDoF)
|
||||
{
|
||||
_SetupHumanSkeleton = typeof(AvatarSetupTool).GetMethod(nameof(SetupHumanSkeleton), (BindingFlags)(-1));
|
||||
skeletonBones = Array.Empty<SkeletonBone>();
|
||||
hasTranslationDoF = false;
|
||||
|
||||
_SetupHumanSkeleton?.Invoke(null, new object[]
|
||||
{
|
||||
modelPrefab,
|
||||
humanBoneMappingArray,
|
||||
skeletonBones,
|
||||
hasTranslationDoF
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// AvatarSetupTools
|
||||
// AvatarBuilder.BuildHumanAvatar
|
||||
// AvatarConfigurationStage.CreateStage
|
||||
// AssetImporterTabbedEditor
|
||||
// ModelImporterRigEditor
|
||||
|
||||
#if TESTING
|
||||
[MenuItem("Tools/Copy Hierarchy Array")]
|
||||
static void _Copy(MenuCommand command)
|
||||
{
|
||||
var gameObject = Selection.activeGameObject;
|
||||
var sb = new System.Text.StringBuilder();
|
||||
|
||||
void Traverse(Transform tr)
|
||||
{
|
||||
sb.AppendLine(tr.name);
|
||||
foreach (Transform child in tr)
|
||||
{
|
||||
Traverse(child);
|
||||
}
|
||||
}
|
||||
|
||||
Traverse(gameObject.transform);
|
||||
EditorGUIUtility.systemCopyBuffer = sb.ToString();
|
||||
}
|
||||
|
||||
[MenuItem("Tools/Setup Humanoid")]
|
||||
static void _Do(MenuCommand command)
|
||||
{
|
||||
var gameObject = Selection.activeGameObject;
|
||||
// SetupHumanSkeleton(go, ref humanBoneMappingArray, out var skeletonBones, out var hasTranslationDoF);
|
||||
AddAvatarToGameObject(gameObject);
|
||||
}
|
||||
|
||||
[MenuItem("Tools/Open Avatar Editor")]
|
||||
static void _OpenEditor(MenuCommand command)
|
||||
{
|
||||
var gameObject = Selection.activeGameObject;
|
||||
var avatar = gameObject.GetComponent<Animator>().avatar;
|
||||
var e = (AvatarEditor) Editor.CreateEditor(avatar, typeof(AvatarEditor));
|
||||
e.m_CameFromImportSettings = true;
|
||||
Selection.activeObject = e;
|
||||
e.SwitchToEditMode();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 977986ddaa6e7594c81ccb48155a39a1
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"reference": "GUID:343deaaf83e0cee4ca978e7df0b80d21"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9c9262dcd4069cd4aafbfe7eabf0bf41
|
||||
AssemblyDefinitionReferenceImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using UnityEditor;
|
||||
using UnityEditor.AssetImporters;
|
||||
using UnityEngine;
|
||||
|
||||
[assembly: InternalsVisibleTo("UnityGLTFEditor")]
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
internal class UnityGLTFTabbedEditor : AssetImporterTabbedEditor
|
||||
{
|
||||
private readonly List<GltfAssetImporterTab> _tabs = new List<GltfAssetImporterTab>();
|
||||
|
||||
protected void AddTab(GltfAssetImporterTab tab)
|
||||
{
|
||||
if (!_tabs.Contains(tab)) _tabs.Add(tab);
|
||||
tabs = _tabs.Select(x => (BaseAssetImporterTabUI) x).ToArray();
|
||||
m_TabNames = _tabs.Select(t => t.Label).ToArray();
|
||||
}
|
||||
|
||||
public GltfAssetImporterTab GetTab(int index)
|
||||
{
|
||||
if (_tabs == null || _tabs.Count < 1) return null;
|
||||
if (index < 0) index = 0;
|
||||
if (index >= _tabs.Count) index = _tabs.Count - 1;
|
||||
return _tabs[index];
|
||||
}
|
||||
|
||||
public override void OnEnable() => base.OnEnable();
|
||||
}
|
||||
|
||||
internal class GltfAssetImporterTab : BaseAssetImporterTabUI
|
||||
{
|
||||
internal readonly string Label;
|
||||
private readonly Action _tabGui;
|
||||
|
||||
public GltfAssetImporterTab(AssetImporterEditor panelContainer, string label, Action tabGui) : base(panelContainer)
|
||||
{
|
||||
this.Label = label;
|
||||
this._tabGui = tabGui;
|
||||
}
|
||||
|
||||
internal override void OnEnable() { }
|
||||
public override void OnInspectorGUI() => _tabGui?.Invoke();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 198f536c3cf84dfe9d5617d32d40d7b0
|
||||
timeCreated: 1678788492
|
||||
@@ -0,0 +1,25 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public interface IUnityGltfShaderUpgradeMeta
|
||||
{
|
||||
Shader SourceShader { get; }
|
||||
bool IsUnlit { get; }
|
||||
bool IsTransparent { get; }
|
||||
bool IsDoublesided { get; }
|
||||
}
|
||||
|
||||
public class UnityGltfShaderUpgradeMeta : ScriptableObject
|
||||
{
|
||||
public Shader sourceShader;
|
||||
public bool isTransparent = false;
|
||||
public bool isDoublesided = false;
|
||||
|
||||
internal string GenerateNameString()
|
||||
{
|
||||
var isUnlit = sourceShader && sourceShader.name.Contains("Unlit");
|
||||
return (isTransparent ? "_tr" : "") + (isDoublesided ? "_ds" : "") + (isUnlit ? "_unlit" : "");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 26fa35d7d798408bb796a50daa5a8a6f
|
||||
timeCreated: 1677690411
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fa6ac3fcfd75d5c469e07cedac8f2f57
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,278 @@
|
||||
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt)
|
||||
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityEditor
|
||||
{
|
||||
internal class PbrShaderGUI : ShaderGUI
|
||||
{
|
||||
private enum WorkflowMode
|
||||
{
|
||||
SpecularGlossiness,
|
||||
MetallicRoughness,
|
||||
Unlit
|
||||
}
|
||||
|
||||
public enum BlendMode
|
||||
{
|
||||
Opaque,
|
||||
Mask,
|
||||
Blend
|
||||
}
|
||||
|
||||
private static class Styles
|
||||
{
|
||||
public static GUIContent albedoText = new GUIContent("Base Color", "Albedo (RGB) and Transparency (A)");
|
||||
public static GUIContent vertexColorText = new GUIContent("Apply Vertex Colors", "Process vertex colors");
|
||||
public static GUIContent alphaCutoffText = new GUIContent("Alpha Cutoff", "Threshold for alpha cutoff");
|
||||
public static GUIContent specularMapText = new GUIContent("Spec Gloss", "Specular (RGB) and Glossiness (A)");
|
||||
public static GUIContent metallicMapText = new GUIContent("Metal Rough", "Metallic (B) and Roughness (G)");
|
||||
public static GUIContent metallicText = new GUIContent("Metallic", "Metallic value");
|
||||
public static GUIContent metallicScaleText = new GUIContent("Metallic", "Metallic scale factor");
|
||||
public static GUIContent roughnessText = new GUIContent("Roughness", "Roughness value");
|
||||
|
||||
public static GUIContent roughnessScaleText = new GUIContent("Roughness", "Roughness scale factor");
|
||||
public static GUIContent glossinessText = new GUIContent("Glossiness", "Glossiness value");
|
||||
public static GUIContent glossinessScaleText = new GUIContent("Glossiness", "Glossiness scale factor");
|
||||
public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map");
|
||||
public static GUIContent occlusionText = new GUIContent("Occlusion", "Occlusion (R)");
|
||||
public static GUIContent emissionText = new GUIContent("Emissive", "Emissive (RGB)");
|
||||
|
||||
public static string primaryMapsText = "Main Maps";
|
||||
public static string renderingMode = "Rendering Mode";
|
||||
public static GUIContent emissiveWarning = new GUIContent("Emissive value is animated but the material has not been configured to support emissive. Please make sure the material itself has some amount of emissive.");
|
||||
public static readonly string[] blendNames = Enum.GetNames(typeof(BlendMode));
|
||||
}
|
||||
|
||||
MaterialProperty blendMode = null;
|
||||
MaterialProperty albedoMap = null;
|
||||
MaterialProperty albedoColor = null;
|
||||
MaterialProperty vertexColors = null;
|
||||
MaterialProperty alphaCutoff = null;
|
||||
MaterialProperty specularMap = null;
|
||||
MaterialProperty specularColor = null;
|
||||
MaterialProperty metallicMap = null;
|
||||
MaterialProperty metallic = null;
|
||||
MaterialProperty smoothness = null;
|
||||
MaterialProperty bumpScale = null;
|
||||
MaterialProperty bumpMap = null;
|
||||
MaterialProperty occlusionStrength = null;
|
||||
MaterialProperty occlusionMap = null;
|
||||
MaterialProperty emissionColor = null;
|
||||
MaterialProperty emissionMap = null;
|
||||
|
||||
MaterialEditor m_MaterialEditor;
|
||||
WorkflowMode m_WorkflowMode = WorkflowMode.MetallicRoughness;
|
||||
|
||||
bool m_FirstTimeApply = true;
|
||||
|
||||
public void FindProperties(MaterialProperty[] props)
|
||||
{
|
||||
blendMode = FindProperty("_Mode", props);
|
||||
albedoMap = FindProperty("_MainTex", props);
|
||||
albedoColor = FindProperty("_Color", props);
|
||||
vertexColors = FindProperty("_VertexColors", props);
|
||||
alphaCutoff = FindProperty("_Cutoff", props);
|
||||
specularMap = FindProperty("_SpecGlossMap", props, false);
|
||||
specularColor = FindProperty("_SpecColor", props, false);
|
||||
metallicMap = FindProperty("_MetallicGlossMap", props, false);
|
||||
metallic = FindProperty("_Metallic", props, false);
|
||||
if (specularMap != null && specularColor != null)
|
||||
m_WorkflowMode = WorkflowMode.SpecularGlossiness;
|
||||
else if (metallicMap != null && metallic != null)
|
||||
m_WorkflowMode = WorkflowMode.MetallicRoughness;
|
||||
else
|
||||
m_WorkflowMode = WorkflowMode.Unlit;
|
||||
smoothness = FindProperty("_Glossiness", props);
|
||||
bumpScale = FindProperty("_BumpScale", props);
|
||||
bumpMap = FindProperty("_BumpMap", props);
|
||||
occlusionStrength = FindProperty("_OcclusionStrength", props);
|
||||
occlusionMap = FindProperty("_OcclusionMap", props);
|
||||
emissionColor = FindProperty("_EmissionColor", props);
|
||||
emissionMap = FindProperty("_EmissionMap", props);
|
||||
}
|
||||
|
||||
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props)
|
||||
{
|
||||
FindProperties(props); // MaterialProperties can be animated so we do not cache them but fetch them every event to ensure animated values are updated correctly
|
||||
m_MaterialEditor = materialEditor;
|
||||
Material material = materialEditor.target as Material;
|
||||
|
||||
// Make sure that needed setup (ie keywords/renderqueue) are set up if we're switching some existing
|
||||
// material to a standard shader.
|
||||
// Do this before any GUI code has been issued to prevent layout issues in subsequent GUILayout statements (case 780071)
|
||||
if (m_FirstTimeApply)
|
||||
{
|
||||
MaterialChanged(material, m_WorkflowMode);
|
||||
m_FirstTimeApply = false;
|
||||
}
|
||||
|
||||
ShaderPropertiesGUI(material);
|
||||
}
|
||||
|
||||
public void ShaderPropertiesGUI(Material material)
|
||||
{
|
||||
// Use default labelWidth
|
||||
EditorGUIUtility.labelWidth = 0f;
|
||||
|
||||
// Detect any changes to the material
|
||||
EditorGUI.BeginChangeCheck();
|
||||
{
|
||||
BlendModePopup();
|
||||
|
||||
// Primary properties
|
||||
GUILayout.Label(Styles.primaryMapsText, EditorStyles.boldLabel);
|
||||
DoAlbedoArea(material);
|
||||
DoSpecularMetallicArea();
|
||||
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMap, bumpMap.textureValue != null ? bumpScale : null);
|
||||
m_MaterialEditor.TexturePropertySingleLine(Styles.occlusionText, occlusionMap, occlusionMap.textureValue != null ? occlusionStrength : null);
|
||||
DoEmissionArea(material);
|
||||
|
||||
EditorGUILayout.Space();
|
||||
}
|
||||
if (EditorGUI.EndChangeCheck())
|
||||
{
|
||||
foreach (var obj in blendMode.targets)
|
||||
MaterialChanged((Material)obj, m_WorkflowMode);
|
||||
}
|
||||
}
|
||||
|
||||
internal void DetermineWorkflow(MaterialProperty[] props)
|
||||
{
|
||||
if (FindProperty("_SpecGlossMap", props, false) != null && FindProperty("_SpecColor", props, false) != null)
|
||||
m_WorkflowMode = WorkflowMode.SpecularGlossiness;
|
||||
else if (FindProperty("_MetallicGlossMap", props, false) != null && FindProperty("_Metallic", props, false) != null)
|
||||
m_WorkflowMode = WorkflowMode.MetallicRoughness;
|
||||
else
|
||||
m_WorkflowMode = WorkflowMode.Unlit;
|
||||
}
|
||||
|
||||
void BlendModePopup()
|
||||
{
|
||||
EditorGUI.showMixedValue = blendMode.hasMixedValue;
|
||||
var mode = (BlendMode)blendMode.floatValue;
|
||||
|
||||
EditorGUI.BeginChangeCheck();
|
||||
mode = (BlendMode)EditorGUILayout.Popup(Styles.renderingMode, (int)mode, Styles.blendNames);
|
||||
if (EditorGUI.EndChangeCheck())
|
||||
{
|
||||
m_MaterialEditor.RegisterPropertyChangeUndo("Rendering Mode");
|
||||
blendMode.floatValue = (float)mode;
|
||||
}
|
||||
|
||||
EditorGUI.showMixedValue = false;
|
||||
}
|
||||
|
||||
void DoAlbedoArea(Material material)
|
||||
{
|
||||
m_MaterialEditor.TexturePropertySingleLine(Styles.albedoText, albedoMap, albedoColor);
|
||||
m_MaterialEditor.ShaderProperty(vertexColors, Styles.vertexColorText, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1);
|
||||
|
||||
if (((BlendMode)material.GetFloat("_Mode") == BlendMode.Mask))
|
||||
{
|
||||
m_MaterialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1);
|
||||
}
|
||||
}
|
||||
|
||||
void DoEmissionArea(Material material)
|
||||
{
|
||||
bool hadEmissionTexture = emissionMap.textureValue != null;
|
||||
|
||||
// Texture and HDR color controls
|
||||
m_MaterialEditor.TexturePropertySingleLine(Styles.emissionText, emissionMap, emissionColor);
|
||||
|
||||
// If texture was assigned and color was black set color to white
|
||||
float brightness = emissionColor.colorValue.maxColorComponent;
|
||||
if (emissionMap.textureValue != null && !hadEmissionTexture && brightness <= 0f)
|
||||
emissionColor.colorValue = Color.white;
|
||||
}
|
||||
|
||||
void DoSpecularMetallicArea()
|
||||
{
|
||||
bool hasGlossMap = false;
|
||||
if (m_WorkflowMode == WorkflowMode.SpecularGlossiness)
|
||||
{
|
||||
hasGlossMap = specularMap.textureValue != null;
|
||||
m_MaterialEditor.TexturePropertySingleLine(Styles.specularMapText, specularMap, hasGlossMap ? null : specularColor);
|
||||
m_MaterialEditor.ShaderProperty(smoothness, hasGlossMap ? Styles.glossinessScaleText : Styles.glossinessText, 2);
|
||||
}
|
||||
else if (m_WorkflowMode == WorkflowMode.MetallicRoughness)
|
||||
{
|
||||
hasGlossMap = metallicMap.textureValue != null;
|
||||
m_MaterialEditor.TexturePropertySingleLine(Styles.metallicMapText, metallicMap);
|
||||
m_MaterialEditor.ShaderProperty(metallic, hasGlossMap ? Styles.metallicScaleText : Styles.metallicText, 2);
|
||||
m_MaterialEditor.ShaderProperty(smoothness, hasGlossMap ? Styles.roughnessScaleText : Styles.roughnessText, 2);
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetupMaterialWithBlendMode(Material material, BlendMode blendMode, float alphaCutoff)
|
||||
{
|
||||
switch (blendMode)
|
||||
{
|
||||
case BlendMode.Opaque:
|
||||
material.SetOverrideTag("RenderType", "Opaque");
|
||||
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
|
||||
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
|
||||
material.SetInt("_ZWrite", 1);
|
||||
material.DisableKeyword("_ALPHATEST_ON");
|
||||
material.DisableKeyword("_ALPHABLEND_ON");
|
||||
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
|
||||
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Geometry;
|
||||
break;
|
||||
case BlendMode.Mask:
|
||||
material.SetOverrideTag("RenderType", "TransparentCutout");
|
||||
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
|
||||
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
|
||||
material.SetInt("_ZWrite", 1);
|
||||
material.EnableKeyword("_ALPHATEST_ON");
|
||||
material.DisableKeyword("_ALPHABLEND_ON");
|
||||
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
|
||||
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest;
|
||||
material.SetFloat("_Cutoff", alphaCutoff);
|
||||
break;
|
||||
case BlendMode.Blend:
|
||||
material.SetOverrideTag("RenderType", "Transparent");
|
||||
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
|
||||
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
|
||||
material.SetInt("_ZWrite", 0);
|
||||
material.DisableKeyword("_ALPHATEST_ON");
|
||||
material.EnableKeyword("_ALPHABLEND_ON");
|
||||
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
|
||||
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
|
||||
break;
|
||||
}
|
||||
|
||||
material.SetFloat("_Mode", (float)blendMode);
|
||||
}
|
||||
|
||||
static void SetMaterialKeywords(Material material, WorkflowMode workflowMode)
|
||||
{
|
||||
// Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation
|
||||
// (MaterialProperty value might come from renderer material property block)
|
||||
SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap"));
|
||||
if (workflowMode == WorkflowMode.SpecularGlossiness)
|
||||
SetKeyword(material, "_SPECGLOSSMAP", material.GetTexture("_SpecGlossMap"));
|
||||
else if (workflowMode == WorkflowMode.MetallicRoughness)
|
||||
SetKeyword(material, "_METALLICGLOSSMAP", material.GetTexture("_MetallicGlossMap"));
|
||||
|
||||
bool shouldEmissionBeEnabled = material.GetColor("_EmissionColor") != Color.black;
|
||||
SetKeyword(material, "_EMISSION", shouldEmissionBeEnabled);
|
||||
}
|
||||
|
||||
static void MaterialChanged(Material material, WorkflowMode workflowMode)
|
||||
{
|
||||
SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode"), material.GetFloat("_Cutoff"));
|
||||
|
||||
SetMaterialKeywords(material, workflowMode);
|
||||
}
|
||||
|
||||
static void SetKeyword(Material m, string keyword, bool state)
|
||||
{
|
||||
if (state)
|
||||
m.EnableKeyword(keyword);
|
||||
else
|
||||
m.DisableKeyword(keyword);
|
||||
}
|
||||
}
|
||||
} // namespace UnityEditor
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bc50aae8534b8c442a9e309b546db682
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4f9d8791ed9e9674d871b47bf1c186ea
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8f708e30d7503fc42998ad4dc358d3d5
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+496
@@ -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
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7fd38ac84daf5a14180dde4bc5949e25
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+56
@@ -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
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0a60cd145bbb31542ab7932da93de3f3
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+105
@@ -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
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fe431e399c52971408121c6c40cde979
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+26
@@ -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
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 511b21f4c3344c54689aed102b11724a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"reference": "GUID:be0903cd8e1546f498710afdc59db5eb"
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d60ff41bbebf9024dac1e4f0dc004a57
|
||||
AssemblyDefinitionReferenceImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9f369a0c649cfa54799cb62645da047f
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
#if !NO_INTERNALS_ACCESS
|
||||
#if UNITY_2021_3_OR_NEWER
|
||||
#define HAVE_CATEGORIES
|
||||
#endif
|
||||
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
// matches ShaderGraphLitGUI.cs
|
||||
public class PBRGraphUniversalGUI : PBRGraphGUI
|
||||
{
|
||||
#if HAVE_CATEGORIES
|
||||
private PropertyInfo materialEditorPropertyAccessor;
|
||||
private ShaderGraphLitGUI litGuiForwarder;
|
||||
|
||||
public override void ValidateMaterial(Material material)
|
||||
{
|
||||
if (material == null) throw new ArgumentNullException(nameof(material));
|
||||
|
||||
base.ValidateMaterial(material);
|
||||
|
||||
var automaticRenderQueue = GetAutomaticQueueControlSetting(material);
|
||||
BaseShaderGUI.UpdateMaterialSurfaceOptions(material, automaticRenderQueue);
|
||||
}
|
||||
|
||||
protected override void DrawSurfaceOptions(Material material)
|
||||
{
|
||||
if (material == null) throw new ArgumentNullException(nameof(material));
|
||||
|
||||
// Use default labelWidth
|
||||
EditorGUIUtility.labelWidth = 0f;
|
||||
|
||||
if (litGuiForwarder == null) litGuiForwarder = new ShaderGraphLitGUI();
|
||||
if (materialEditorPropertyAccessor == null) materialEditorPropertyAccessor = typeof(BaseShaderGUI).GetProperty("materialEditor", (BindingFlags) (-1));
|
||||
if (materialEditorPropertyAccessor != null) materialEditorPropertyAccessor.SetValue(litGuiForwarder, materialEditor); // forwarder.materialEditor = materialEditor;
|
||||
|
||||
litGuiForwarder.FindProperties(properties);
|
||||
litGuiForwarder.workflowMode = null;
|
||||
litGuiForwarder.DrawSurfaceOptions(material);
|
||||
}
|
||||
|
||||
protected override void DrawAdvancedOptions(Material material)
|
||||
{
|
||||
base.DrawAdvancedOptions(material);
|
||||
|
||||
materialEditor.DoubleSidedGIField();
|
||||
materialEditor.LightmapEmissionFlagsProperty(0, enabled: true, ignoreEmissionColor: true);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 86a2b51891c425a468a0a4d61f8b2a6a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"reference": "GUID:c579267770062bf448e75eb160330b7f"
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cd3b604407efbd641a4d40520de58a76
|
||||
AssemblyDefinitionReferenceImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1 @@
|
||||
internal class NoCompilationWarning { }
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4ea8663e2a74bdc4cb6f6d53769532df
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,240 @@
|
||||
using System.Linq;
|
||||
using GLTF.Schema;
|
||||
using UnityEngine;
|
||||
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public static class ShaderConverters
|
||||
{
|
||||
[InitializeOnLoadMethod]
|
||||
static void InitShaderConverters()
|
||||
{
|
||||
GLTFMaterialHelper.RegisterMaterialConversionToGLTF(ConvertStandardAndURPLit);
|
||||
GLTFMaterialHelper.RegisterMaterialConversionToGLTF(ConvertUnityGLTFGraphs);
|
||||
}
|
||||
|
||||
private static bool ConvertUnityGLTFGraphs(Material material, Shader oldShader, Shader newShader)
|
||||
{
|
||||
// update legacy shaders that didn't have material overrides available
|
||||
if (oldShader.name.StartsWith("Hidden/UnityGLTF/PBRGraph") || oldShader.name.StartsWith("Hidden/UnityGLTF/UnlitGraph"))
|
||||
{
|
||||
material.shader = newShader;
|
||||
|
||||
var meta = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(material.shader)) as IUnityGltfShaderUpgradeMeta;
|
||||
if (meta != null)
|
||||
{
|
||||
// Debug.Log("Updating shader from " + material.shader + " to " + meta.SourceShader +
|
||||
// " (transparent: " + meta.IsTransparent + ", double sided: " + meta.IsDoublesided + ")");
|
||||
|
||||
var isUnlit = meta.SourceShader.name.Contains("Unlit");
|
||||
material.shader = meta.SourceShader;
|
||||
|
||||
var mapper = isUnlit ? (IUniformMap) new UnlitMap(material) : new PBRGraphMap(material);
|
||||
if (meta.IsTransparent)
|
||||
mapper.AlphaMode = AlphaMode.BLEND;
|
||||
if (meta.IsDoublesided)
|
||||
mapper.DoubleSided = true;
|
||||
|
||||
EditorUtility.SetDirty(material);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (oldShader.name != "UnityGLTF/UnlitGraph" && oldShader.name != "UnityGLTF/PBRGraph") return false;
|
||||
|
||||
material.shader = newShader;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool ConvertStandardAndURPLit(Material material, Shader oldShader, Shader newShader)
|
||||
{
|
||||
// Conversion time!
|
||||
// convert from
|
||||
// - "Standard"
|
||||
// - "URP/Lit"
|
||||
|
||||
if (oldShader.name != StandardShader && oldShader.name != URPLitShader) return false;
|
||||
|
||||
var isStandard = oldShader.name == StandardShader;
|
||||
var needsEmissiveColorSpaceConversion = isStandard && QualitySettings.activeColorSpace == ColorSpace.Linear;
|
||||
var colorProp = oldShader.name == StandardShader ? _Color : _BaseColor;
|
||||
var colorTexProp = oldShader.name == StandardShader ? _MainTex : _BaseMap;
|
||||
|
||||
var color = material.GetColor(colorProp);
|
||||
var albedo = material.GetTexture(colorTexProp);
|
||||
var albedoOffset = material.GetTextureOffset(colorTexProp);
|
||||
var albedoTiling = material.GetTextureScale(colorTexProp);
|
||||
|
||||
var metallic = material.GetFloat(_Metallic);
|
||||
var smoothness = material.HasProperty(_Smoothness) ? material.GetFloat(_Smoothness) : material.GetFloat(_Glossiness);
|
||||
var metallicGloss = material.GetTexture(_MetallicGlossMap);
|
||||
var normal = material.GetTexture(_BumpMap);
|
||||
var normalStrength = material.GetFloat(_BumpScale);
|
||||
var occlusion = material.GetTexture(_OcclusionMap);
|
||||
var occlusionStrength = material.GetFloat(_Strength);
|
||||
var emission = material.GetTexture(_EmissionMap);
|
||||
var emissionColor = material.GetColor(_EmissionColor);
|
||||
var cutoff = material.GetFloat(_Cutoff);
|
||||
|
||||
var isCutoff = material.IsKeywordEnabled("_ALPHATEST_ON") || material.IsKeywordEnabled("_BUILTIN_ALPHATEST_ON");
|
||||
|
||||
material.shader = newShader;
|
||||
|
||||
material.SetColor(baseColorFactor, color);
|
||||
material.SetTexture(baseColorTexture, albedo);
|
||||
material.SetTextureOffset(baseColorTexture, albedoOffset);
|
||||
material.SetTextureScale(baseColorTexture, albedoTiling);
|
||||
if (albedoOffset != Vector2.zero || albedoTiling != Vector2.one)
|
||||
GLTFMaterialHelper.SetKeyword(material, "_TEXTURE_TRANSFORM", true);
|
||||
|
||||
material.SetFloat(metallicFactor, metallic);
|
||||
material.SetFloat(roughnessFactor, 1 - smoothness);
|
||||
const string ConversionWarning = "The Metallic (R) Smoothness (A) texture needs to be converted to Roughness (B) Metallic (G). ";
|
||||
#if UNITY_EDITOR && UNITY_2022_1_OR_NEWER
|
||||
var importerPath = AssetDatabase.GetAssetPath(metallicGloss);
|
||||
var importer = AssetImporter.GetAtPath(importerPath) as TextureImporter;
|
||||
if (importer && importer.swizzleG != TextureImporterSwizzle.OneMinusR) // can't really detect if this has been done on the texture already, this is just a heuristic...
|
||||
{
|
||||
if (EditorUtility.DisplayDialog("Texture Conversion",
|
||||
ConversionWarning + "This is done by swizzling texture channels in the importer. Do you want to proceed?",
|
||||
"OK", DialogOptOutDecisionType.ForThisSession, nameof(GLTFMaterialHelper) + "_texture_conversion"))
|
||||
{
|
||||
importer.swizzleR = TextureImporterSwizzle.B;
|
||||
importer.swizzleG = TextureImporterSwizzle.OneMinusR;
|
||||
importer.swizzleB = TextureImporterSwizzle.G;
|
||||
Undo.RegisterImporterUndo(importerPath, "Texture Swizzles (M__G > _RM_)");
|
||||
importer.SaveAndReimport();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogWarning(ConversionWarning + "This currently needs to be done manually. Please swap channels in an external software.", material);
|
||||
}
|
||||
#else
|
||||
if (metallicGloss)
|
||||
Debug.LogWarning(ConversionWarning + "This currently needs to be done manually. Please swap channels in an external software.", material);
|
||||
#endif
|
||||
// TODO: convert metallicGloss to metallicRoughnessTexture format: Metallic (R) + Smoothness (A) → Roughness (G) + Metallic (B)
|
||||
// TODO: when smoothness is not 0 or 1 and there's a texture, need to convert to a texture and set roughness = 1, otherwise the math doesn't match
|
||||
// TODO: figure out where to put the newly created texture, and how to avoid re-creating it several times when multiple materials may use it.
|
||||
material.SetTexture(metallicRoughnessTexture, metallicGloss);
|
||||
material.SetTexture(normalTexture, normal);
|
||||
material.SetFloat(normalScale, normalStrength);
|
||||
material.SetTexture(occlusionTexture, occlusion);
|
||||
material.SetFloat(occlusionStrength1, occlusionStrength);
|
||||
material.SetTexture(emissiveTexture, emission);
|
||||
material.SetFloat(alphaCutoff, cutoff);
|
||||
if (isCutoff)
|
||||
{
|
||||
GLTFMaterialHelper.SetKeyword(material, "_ALPHATEST", true);
|
||||
GLTFMaterialHelper.SetKeyword(material, "_BUILTIN_ALPHATEST", true);
|
||||
material.EnableKeyword("_BUILTIN_AlphaClip");
|
||||
}
|
||||
|
||||
material.SetColor(emissiveFactor, needsEmissiveColorSpaceConversion ? emissionColor.linear : emissionColor);
|
||||
|
||||
// set the flags on conversion, otherwise it's confusing why they're not on - can't easily replicate the magic that Unity does in their inspectors when changing emissive on/off
|
||||
if (material.globalIlluminationFlags == MaterialGlobalIlluminationFlags.None || material.globalIlluminationFlags == MaterialGlobalIlluminationFlags.EmissiveIsBlack)
|
||||
material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.BakedEmissive;
|
||||
|
||||
// ensure keywords are correctly set after conversion
|
||||
GLTFMaterialHelper.ValidateMaterialKeywords(material);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// ReSharper disable InconsistentNaming
|
||||
private const string StandardShader = "Standard";
|
||||
private const string URPLitShader = "Universal Render Pipeline/Lit";
|
||||
|
||||
// Standard and URP-Lit property names
|
||||
private static readonly int _Color = Shader.PropertyToID("_Color");
|
||||
private static readonly int _BaseColor = Shader.PropertyToID("_BaseColor");
|
||||
private static readonly int _MainTex = Shader.PropertyToID("_MainTex");
|
||||
private static readonly int _BaseMap = Shader.PropertyToID("_BaseMap");
|
||||
private static readonly int _Metallic = Shader.PropertyToID("_Metallic");
|
||||
private static readonly int _Glossiness = Shader.PropertyToID("_Glossiness");
|
||||
private static readonly int _Smoothness = Shader.PropertyToID("_Smoothness");
|
||||
private static readonly int _MetallicGlossMap = Shader.PropertyToID("_MetallicGlossMap");
|
||||
private static readonly int _BumpMap = Shader.PropertyToID("_BumpMap");
|
||||
private static readonly int _BumpScale = Shader.PropertyToID("_BumpScale");
|
||||
private static readonly int _OcclusionMap = Shader.PropertyToID("_OcclusionMap");
|
||||
private static readonly int _Strength = Shader.PropertyToID("_OcclusionStrength");
|
||||
private static readonly int _EmissionMap = Shader.PropertyToID("_EmissionMap");
|
||||
private static readonly int _EmissionColor = Shader.PropertyToID("_EmissionColor");
|
||||
private static readonly int _Cutoff = Shader.PropertyToID("_Cutoff");
|
||||
|
||||
// glTF property names
|
||||
private static readonly int baseColorFactor = Shader.PropertyToID("baseColorFactor");
|
||||
private static readonly int baseColorTexture = Shader.PropertyToID("baseColorTexture");
|
||||
private static readonly int metallicFactor = Shader.PropertyToID("metallicFactor");
|
||||
private static readonly int roughnessFactor = Shader.PropertyToID("roughnessFactor");
|
||||
private static readonly int metallicRoughnessTexture = Shader.PropertyToID("metallicRoughnessTexture");
|
||||
private static readonly int normalTexture = Shader.PropertyToID("normalTexture");
|
||||
private static readonly int normalScale = Shader.PropertyToID("normalScale");
|
||||
private static readonly int occlusionTexture = Shader.PropertyToID("occlusionTexture");
|
||||
private static readonly int occlusionStrength1 = Shader.PropertyToID("occlusionStrength");
|
||||
private static readonly int emissiveTexture = Shader.PropertyToID("emissiveTexture");
|
||||
private static readonly int emissiveFactor = Shader.PropertyToID("emissiveFactor");
|
||||
private static readonly int alphaCutoff = Shader.PropertyToID("alphaCutoff");
|
||||
// ReSharper restore InconsistentNaming
|
||||
|
||||
private static readonly string[] emissivePropNames = new[] { "emissiveFactor", "_EmissionColor" };
|
||||
|
||||
[MenuItem("CONTEXT/Material/UnityGLTF Material Helpers/Convert Emissive Colors > sRGB - weaker, darker")]
|
||||
private static void ConvertToSRGB(MenuCommand command)
|
||||
{
|
||||
if (!(command.context is Material mat)) return;
|
||||
Undo.RegisterCompleteObjectUndo(mat, "Convert emissive colors to sRGB");
|
||||
foreach(var propName in emissivePropNames)
|
||||
if (mat.HasProperty(propName)) mat.SetColor(propName, mat.GetColor(propName).gamma);
|
||||
}
|
||||
|
||||
[MenuItem("CONTEXT/Material/UnityGLTF Material Helpers/Convert Emissive Colors > Linear - brighter, stronger")]
|
||||
private static void ConvertToLinear(MenuCommand command)
|
||||
{
|
||||
if (!(command.context is Material mat)) return;
|
||||
Undo.RegisterCompleteObjectUndo(mat, "Convert emissive colors to sRGB");
|
||||
foreach(var propName in emissivePropNames)
|
||||
if (mat.HasProperty(propName)) mat.SetColor(propName, mat.GetColor(propName).linear);
|
||||
}
|
||||
|
||||
[MenuItem("CONTEXT/Material/UnityGLTF Material Helpers/ Select all materials with this shader", false, -1000)]
|
||||
private static void SelectAllMaterialsWithShader(MenuCommand command)
|
||||
{
|
||||
if (!(command.context is Material mat)) return;
|
||||
var allMaterials = AssetDatabase.FindAssets("t:Material")
|
||||
.Select(AssetDatabase.GUIDToAssetPath)
|
||||
.Select(AssetDatabase.LoadAssetAtPath<Material>)
|
||||
.Where(x => !AssetDatabase.IsSubAsset(x))
|
||||
.Where(x => x.shader == mat.shader)
|
||||
.Cast<Object>()
|
||||
.ToArray();
|
||||
foreach (var obj in allMaterials)
|
||||
EditorGUIUtility.PingObject(obj);
|
||||
Selection.objects = allMaterials;
|
||||
}
|
||||
|
||||
private static bool TryGetMetadataOfType<T>(Shader shader, out T obj) where T : ScriptableObject
|
||||
{
|
||||
obj = null;
|
||||
|
||||
var path = AssetDatabase.GetAssetPath(shader);
|
||||
foreach (var asset in AssetDatabase.LoadAllAssetsAtPath(path))
|
||||
{
|
||||
if (asset is T metadataAsset)
|
||||
{
|
||||
obj = metadataAsset;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 77ad4bb761964b0da3ccf68f6b649aab
|
||||
timeCreated: 1677764644
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "UnityGLTF.ShaderGraph",
|
||||
"rootNamespace": "",
|
||||
"references": [
|
||||
"GUID:be0903cd8e1546f498710afdc59db5eb",
|
||||
"GUID:18d18f811ba286c49814567a3cfba688",
|
||||
"GUID:40f39bff7bc9be34182ebe488fcf8228"
|
||||
],
|
||||
"includePlatforms": [
|
||||
"Editor"
|
||||
],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": false,
|
||||
"overrideReferences": true,
|
||||
"precompiledReferences": [],
|
||||
"autoReferenced": false,
|
||||
"defineConstraints": [
|
||||
"UNITY_2019_4_OR_NEWER"
|
||||
],
|
||||
"versionDefines": [
|
||||
{
|
||||
"name": "com.unity.modules.imageconversion",
|
||||
"expression": "0.0.0",
|
||||
"define": "NO_INTERNALS_ACCESS"
|
||||
}
|
||||
],
|
||||
"noEngineReferences": false
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 17181a83a8717a34d8ce050af64edd83
|
||||
AssemblyDefinitionImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Reference in New Issue
Block a user