bug fix
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ad85f72cb68a7854d8bd33e064340c2b
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,40 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public class AsyncCoroutineHelper : MonoBehaviour
|
||||
{
|
||||
public float BudgetPerFrameInSeconds = 0.01f;
|
||||
|
||||
private WaitForEndOfFrame _waitForEndOfFrame = new WaitForEndOfFrame();
|
||||
private float _timeout;
|
||||
|
||||
public async Task YieldOnTimeout()
|
||||
{
|
||||
if (Time.realtimeSinceStartup > _timeout)
|
||||
{
|
||||
await Task.Yield();
|
||||
_timeout = Time.realtimeSinceStartup + BudgetPerFrameInSeconds;
|
||||
}
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
_timeout = Time.realtimeSinceStartup + BudgetPerFrameInSeconds;
|
||||
|
||||
StartCoroutine(ResetFrameTimeout());
|
||||
}
|
||||
|
||||
private IEnumerator ResetFrameTimeout()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
yield return _waitForEndOfFrame;
|
||||
_timeout = Time.realtimeSinceStartup + BudgetPerFrameInSeconds;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f51ceb82926c0a44394654b191b00336
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,18 @@
|
||||
#if UNITY_2017_1_OR_NEWER
|
||||
using System.Collections;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public static class TaskExtensions
|
||||
{
|
||||
public static IEnumerator AsCoroutine(this Task task)
|
||||
{
|
||||
while (!task.IsCompleted)
|
||||
{
|
||||
yield return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7305b2a914e83c142b612e9994f1b483
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6ce40bec54ad382449f80ef0e1028101
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,27 @@
|
||||
#if UNITY_ANIMATION || !UNITY_2019_1_OR_NEWER
|
||||
|
||||
using GLTF;
|
||||
using GLTF.Schema;
|
||||
|
||||
namespace UnityGLTF.Cache
|
||||
{
|
||||
public struct AnimationSamplerCacheData
|
||||
{
|
||||
public AttributeAccessor Input;
|
||||
public AttributeAccessor Output;
|
||||
public InterpolationType Interpolation;
|
||||
}
|
||||
|
||||
public class AnimationCacheData
|
||||
{
|
||||
public UnityEngine.AnimationClip LoadedAnimationClip { get; set; }
|
||||
public AnimationSamplerCacheData[] Samplers { get; set; }
|
||||
|
||||
public AnimationCacheData(int samplerCount)
|
||||
{
|
||||
Samplers = new AnimationSamplerCacheData[samplerCount];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5eb5ec69ffa30384786436879a3167a3
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,117 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using System.IO;
|
||||
using GLTF.Schema;
|
||||
|
||||
namespace UnityGLTF.Cache
|
||||
{
|
||||
/// <summary>
|
||||
/// Caches data in order to construct a unity object
|
||||
/// </summary>
|
||||
public class AssetCache : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Streams to the images to be loaded
|
||||
/// </summary>
|
||||
public Stream[] ImageStreamCache { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Loaded raw texture data
|
||||
/// </summary>
|
||||
public Texture2D[] ImageCache { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Textures to be used for assets. Textures from image cache with samplers applied
|
||||
/// </summary>
|
||||
public TextureCacheData[] TextureCache { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Cache for materials to be applied to the meshes
|
||||
/// </summary>
|
||||
public MaterialCacheData[] MaterialCache { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Byte buffers that represent the binary contents that get parsed
|
||||
/// </summary>
|
||||
public BufferCacheData[] BufferCache { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Cache of loaded meshes
|
||||
/// </summary>
|
||||
public MeshCacheData[] MeshCache { get; private set; }
|
||||
|
||||
#if UNITY_ANIMATION || !UNITY_2019_1_OR_NEWER
|
||||
/// <summary>
|
||||
/// Cache of loaded animations
|
||||
/// </summary>
|
||||
public AnimationCacheData[] AnimationCache { get; private set; }
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Cache of loaded node objects
|
||||
/// </summary>
|
||||
public GameObject[] NodeCache { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates an asset cache which caches objects used in scene
|
||||
/// </summary>
|
||||
/// <param name="root">A glTF root whose assets will eventually be cached here</param>
|
||||
public AssetCache(GLTFRoot root)
|
||||
{
|
||||
ImageCache = new Texture2D[root.Images?.Count ?? 0];
|
||||
ImageStreamCache = new Stream[ImageCache.Length];
|
||||
TextureCache = new TextureCacheData[root.Textures?.Count ?? 0];
|
||||
MaterialCache = new MaterialCacheData[root.Materials?.Count ?? 0];
|
||||
BufferCache = new BufferCacheData[root.Buffers?.Count ?? 0];
|
||||
MeshCache = new MeshCacheData[root.Meshes?.Count ?? 0];
|
||||
|
||||
NodeCache = new GameObject[root.Nodes?.Count ?? 0];
|
||||
#if UNITY_ANIMATION || !UNITY_2019_1_OR_NEWER
|
||||
AnimationCache = new AnimationCacheData[root.Animations?.Count ?? 0];
|
||||
#endif
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (ImageStreamCache != null)
|
||||
{
|
||||
foreach (var stream in ImageStreamCache)
|
||||
{
|
||||
stream?.Dispose();
|
||||
}
|
||||
|
||||
ImageStreamCache = null;
|
||||
}
|
||||
|
||||
ImageCache = null;
|
||||
TextureCache = null;
|
||||
MaterialCache = null;
|
||||
if (BufferCache != null)
|
||||
{
|
||||
foreach (BufferCacheData bufferCacheData in BufferCache)
|
||||
{
|
||||
if (bufferCacheData != null)
|
||||
{
|
||||
if (bufferCacheData.Stream != null)
|
||||
{
|
||||
#if !WINDOWS_UWP
|
||||
bufferCacheData.Stream.Close();
|
||||
#else
|
||||
bufferCacheData.Stream.Dispose();
|
||||
#endif
|
||||
}
|
||||
|
||||
bufferCacheData.Dispose();
|
||||
}
|
||||
}
|
||||
BufferCache = null;
|
||||
}
|
||||
|
||||
MeshCache = null;
|
||||
#if UNITY_ANIMATION || !UNITY_2019_1_OR_NEWER
|
||||
AnimationCache = null;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1bb782a30ee69ac43949c7b27404bb0a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,19 @@
|
||||
using System;
|
||||
|
||||
namespace UnityGLTF.Cache
|
||||
{
|
||||
public class BufferCacheData : IDisposable
|
||||
{
|
||||
public uint ChunkOffset { get; set; }
|
||||
public System.IO.Stream Stream { get; set; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Stream != null)
|
||||
{
|
||||
Stream.Dispose();
|
||||
Stream = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3ede042e9106e314a9c2fc3727c636af
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,110 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF.Cache
|
||||
{
|
||||
internal static class ExportCache
|
||||
{
|
||||
public const int DefaultCacheSize = 1024;
|
||||
#if UNITY_EDITOR
|
||||
[InitializeOnLoadMethod]
|
||||
private static void Init()
|
||||
{
|
||||
// Keep some files in cache that were last exported
|
||||
EditorApplication.quitting += () => Shrink(DefaultCacheSize);
|
||||
}
|
||||
|
||||
public static void OpenCacheDirectory()
|
||||
{
|
||||
var dir = CacheDirectory;
|
||||
if(Directory.Exists(dir)) EditorUtility.RevealInFinder(dir);
|
||||
else Debug.LogWarning($"Cache directory does not exist: {dir}");
|
||||
}
|
||||
#endif
|
||||
|
||||
public static string CacheDirectory
|
||||
{
|
||||
get
|
||||
{
|
||||
var tempDirectory = Path.Combine(Application.temporaryCachePath, "UnityGLTF");
|
||||
return tempDirectory;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool TryGetBytes(Object asset, string seed, out byte[] bytes)
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
var path = CacheDirectory + "/" + GlobalObjectId.GetGlobalObjectIdSlow(asset) + seed;
|
||||
if (File.Exists(path))
|
||||
{
|
||||
bytes = File.ReadAllBytes(path);
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
bytes = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void AddBytes(Object asset, string seed, byte[] bytes)
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
var dir = CacheDirectory;
|
||||
Directory.CreateDirectory(dir);
|
||||
var path = dir + "/" + GlobalObjectId.GetGlobalObjectIdSlow(asset) + seed;
|
||||
// Debug.Log($"Writing {bytes.Length} bytes to cache: {path}");
|
||||
File.WriteAllBytes(path, bytes);
|
||||
#endif
|
||||
}
|
||||
|
||||
public static void Clear()
|
||||
{
|
||||
var dir = CacheDirectory;
|
||||
if (Directory.Exists(dir))
|
||||
{
|
||||
Directory.Delete(dir, true);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Shrink(int maxCacheSizeInMB)
|
||||
{
|
||||
if (maxCacheSizeInMB <= 0)
|
||||
{
|
||||
Clear();
|
||||
return;
|
||||
}
|
||||
|
||||
var maxCacheSize = maxCacheSizeInMB * 1024 * 1024;
|
||||
var files = new List<FileInfo>();
|
||||
var currentSize = CalculateCacheSize(files);
|
||||
if(currentSize <= maxCacheSizeInMB)
|
||||
return;
|
||||
var filesSortedByLastAccess = files.OrderBy(f => f.LastAccessTimeUtc).ToList();
|
||||
foreach (var file in filesSortedByLastAccess)
|
||||
{
|
||||
file.Delete();
|
||||
currentSize -= (int)file.Length;
|
||||
if (currentSize <= maxCacheSize)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public static long CalculateCacheSize(ICollection<FileInfo> files = null)
|
||||
{
|
||||
var dir = CacheDirectory;
|
||||
if (!Directory.Exists(dir)) return 0;
|
||||
var filePaths = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories);
|
||||
long size = 0;
|
||||
foreach (var file in filePaths)
|
||||
{
|
||||
var info = new FileInfo(file);
|
||||
files?.Add(info);
|
||||
size += (long) info.Length;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b67adc482fa84697bf30de7918e7d995
|
||||
timeCreated: 1672777985
|
||||
@@ -0,0 +1,36 @@
|
||||
using GLTF.Schema;
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF.Cache
|
||||
{
|
||||
public class MaterialCacheData : IDisposable
|
||||
{
|
||||
public Material UnityMaterial { get; set; }
|
||||
public Material UnityMaterialWithVertexColor { get; set; }
|
||||
public GLTFMaterial GLTFMaterial { get; set; }
|
||||
|
||||
public Material GetContents(bool useVertexColors)
|
||||
{
|
||||
return useVertexColors ? UnityMaterialWithVertexColor : UnityMaterial;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unloads the materials in this cache.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (UnityMaterial != null)
|
||||
{
|
||||
UnityEngine.Object.Destroy(UnityMaterial);
|
||||
UnityMaterial = null;
|
||||
}
|
||||
|
||||
if (UnityMaterialWithVertexColor != null)
|
||||
{
|
||||
UnityEngine.Object.Destroy(UnityMaterialWithVertexColor);
|
||||
UnityMaterialWithVertexColor = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3046febe680d4eb44b6851e256d7feca
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,31 @@
|
||||
using GLTF;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF.Cache
|
||||
{
|
||||
public class MeshCacheData : IDisposable
|
||||
{
|
||||
public class PrimitiveCacheData
|
||||
{
|
||||
public Dictionary<string, AttributeAccessor> Attributes = new Dictionary<string, AttributeAccessor>(4);
|
||||
public List<Dictionary<string, AttributeAccessor>> Targets = new List<Dictionary<string, AttributeAccessor>>(4);
|
||||
}
|
||||
|
||||
public List<PrimitiveCacheData> Primitives = new List<PrimitiveCacheData>(5);
|
||||
public Mesh LoadedMesh { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Unloads the meshes in this cache.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (LoadedMesh != null)
|
||||
{
|
||||
UnityEngine.Object.Destroy(LoadedMesh);
|
||||
LoadedMesh = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7356479b6b440d943adc853e80ead936
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,125 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF.Cache
|
||||
{
|
||||
/// <summary>
|
||||
/// A ref-counted cache data object containing lists of Unity objects that were created for the sake of a GLTF scene/node.
|
||||
/// This supports counting the amount of refcounts that will dispose of itself
|
||||
/// </summary>
|
||||
public class RefCountedCacheData
|
||||
{
|
||||
private bool _isDisposed = false;
|
||||
|
||||
/// <summary>
|
||||
/// Ref count for this cache data.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Initialized to 0. When assigning the cache data to an instantiated GLTF
|
||||
/// object the count will increase.
|
||||
/// </remarks>
|
||||
private int _refCount = 0;
|
||||
private readonly object _refCountLock = new object();
|
||||
|
||||
/// <summary>
|
||||
/// Meshes used by this GLTF node.
|
||||
/// </summary>
|
||||
public MeshCacheData[] MeshCache { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Materials used by this GLTF node.
|
||||
/// </summary>
|
||||
public MaterialCacheData[] MaterialCache { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Textures used by this GLTF node.
|
||||
/// </summary>
|
||||
public TextureCacheData[] TextureCache { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Textures from the AssetCache that might need to be cleaned up
|
||||
/// </summary>
|
||||
public Texture2D[] ImageCache { get; private set; }
|
||||
|
||||
public RefCountedCacheData(MaterialCacheData[] materialCache, MeshCacheData[] meshCache, TextureCacheData[] textureCache, Texture2D[] imageCache)
|
||||
{
|
||||
MaterialCache = materialCache;
|
||||
MeshCache = meshCache;
|
||||
TextureCache = textureCache;
|
||||
ImageCache = imageCache;
|
||||
}
|
||||
|
||||
public void IncreaseRefCount()
|
||||
{
|
||||
if (_isDisposed)
|
||||
{
|
||||
throw new InvalidOperationException("Cannot inscrease the ref count on disposed cache data.");
|
||||
}
|
||||
|
||||
lock (_refCountLock)
|
||||
{
|
||||
_refCount++;
|
||||
}
|
||||
}
|
||||
|
||||
public void DecreaseRefCount()
|
||||
{
|
||||
if (_isDisposed)
|
||||
{
|
||||
throw new InvalidOperationException("Cannot decrease the ref count on disposed cache data.");
|
||||
}
|
||||
|
||||
lock (_refCountLock)
|
||||
{
|
||||
if (_refCount <= 0)
|
||||
{
|
||||
throw new InvalidOperationException("Cannot decrease the cache data ref count below zero.");
|
||||
}
|
||||
|
||||
_refCount--;
|
||||
}
|
||||
|
||||
if (_refCount <= 0)
|
||||
{
|
||||
DestroyCachedData();
|
||||
}
|
||||
}
|
||||
|
||||
private void DestroyCachedData()
|
||||
{
|
||||
// Destroy the cached meshes
|
||||
for (int i = 0; i < MeshCache.Length; i++)
|
||||
{
|
||||
MeshCache[i]?.Dispose();
|
||||
MeshCache[i] = null;
|
||||
}
|
||||
|
||||
// Destroy the cached textures
|
||||
for (int i = 0; i < TextureCache.Length; i++)
|
||||
{
|
||||
TextureCache[i]?.Dispose();
|
||||
TextureCache[i] = null;
|
||||
}
|
||||
|
||||
// Destroy the cached materials
|
||||
for (int i = 0; i < MaterialCache.Length; i++)
|
||||
{
|
||||
MaterialCache[i]?.Dispose();
|
||||
MaterialCache[i] = null;
|
||||
}
|
||||
|
||||
// Destroy the cached images
|
||||
for (int i = 0; i < ImageCache.Length; i++)
|
||||
{
|
||||
if (ImageCache[i] != null)
|
||||
{
|
||||
UnityEngine.Object.Destroy(ImageCache[i]);
|
||||
ImageCache[i] = null;
|
||||
}
|
||||
}
|
||||
|
||||
_isDisposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6acba157038c72d4db902024947d8f94
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,25 @@
|
||||
using GLTF.Schema;
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF.Cache
|
||||
{
|
||||
public class TextureCacheData : IDisposable
|
||||
{
|
||||
public GLTFTexture TextureDefinition;
|
||||
public Texture2D Texture;
|
||||
public bool IsLinear;
|
||||
|
||||
/// <summary>
|
||||
/// Unloads the textures in this cache.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (Texture != null)
|
||||
{
|
||||
UnityEngine.Object.Destroy(Texture);
|
||||
Texture = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2d62214ca8670eb49aa365a9c8a3abd2
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
[Serializable()]
|
||||
public class WebRequestException : Exception
|
||||
{
|
||||
public WebRequestException() : base() { }
|
||||
public WebRequestException(string message) : base(message) { }
|
||||
public WebRequestException(string message, Exception inner) : base(message, inner) { }
|
||||
#if UNITY_WEBREQUEST
|
||||
public WebRequestException(UnityEngine.Networking.UnityWebRequest www) : base(string.Format("Error: {0} when requesting: {1}", www.responseCode, www.url)) { }
|
||||
#endif
|
||||
#if !WINDOWS_UWP
|
||||
protected WebRequestException(System.Runtime.Serialization.SerializationInfo info,
|
||||
System.Runtime.Serialization.StreamingContext context) { }
|
||||
#endif
|
||||
}
|
||||
|
||||
[Serializable()]
|
||||
public class ShaderNotFoundException : Exception
|
||||
{
|
||||
public ShaderNotFoundException() : base() { }
|
||||
public ShaderNotFoundException(string message) : base(message) { }
|
||||
public ShaderNotFoundException(string message, Exception inner) : base(message, inner) { }
|
||||
#if !WINDOWS_UWP
|
||||
protected ShaderNotFoundException(System.Runtime.Serialization.SerializationInfo info,
|
||||
System.Runtime.Serialization.StreamingContext context)
|
||||
{ }
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// GLTFLoad exceptions occur during runtime errors through use of the GLTFSceneImporter
|
||||
/// </summary>
|
||||
public class GLTFLoadException : Exception
|
||||
{
|
||||
public GLTFLoadException() : base() { }
|
||||
public GLTFLoadException(string message) : base(message) { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8d34b5101f1055e429abecbc93c31f69
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8ec62698f7fefc548b07a91ea9bb447a
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Profiling;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF.Extensions
|
||||
{
|
||||
public class KHR_animation_pointer_Resolver
|
||||
{
|
||||
private readonly List<KHR_animation_pointer> registered = new List<KHR_animation_pointer>();
|
||||
private static readonly ProfilerMarker animationPointerResolverMarker = new ProfilerMarker("Resolve Animation Pointer");
|
||||
|
||||
public void Add(KHR_animation_pointer anim)
|
||||
{
|
||||
registered.Add(anim);
|
||||
}
|
||||
|
||||
// private struct MaterialMapping
|
||||
// {
|
||||
// public string propertyName;
|
||||
// public string exportName;
|
||||
// }
|
||||
//
|
||||
// private readonly Dictionary<Material, List<MaterialMapping>> mappings = new Dictionary<Material, List<MaterialMapping>>();
|
||||
//
|
||||
// // TODO: should we use a static switch instead?
|
||||
// public void RegisterMapping(Material mat, string propertyName, string exportedPropertyName)
|
||||
// {
|
||||
// if (!mappings.ContainsKey(mat))
|
||||
// {
|
||||
// mappings.Add(mat, new List<MaterialMapping>());
|
||||
// }
|
||||
// mappings[mat].Add(new MaterialMapping() { propertyName = propertyName, exportName = exportedPropertyName });
|
||||
// }
|
||||
|
||||
public void Resolve(GLTFSceneExporter exporter)
|
||||
{
|
||||
foreach (var reg in registered)
|
||||
{
|
||||
animationPointerResolverMarker.Begin();
|
||||
int id = exporter.GetIndex(reg.animatedObject);
|
||||
switch (reg.animatedObject)
|
||||
{
|
||||
case Light light:
|
||||
reg.path = "/extensions/KHR_lights_punctual/lights/" + id + "/" + reg.propertyBinding;
|
||||
break;
|
||||
case Camera camera:
|
||||
reg.path = "/cameras/" + id + "/" + reg.propertyBinding;
|
||||
break;
|
||||
case SkinnedMeshRenderer smr:
|
||||
if (smr && reg.propertyBinding == "weights")
|
||||
{
|
||||
reg.path = "/nodes/" + id + "/" + reg.propertyBinding;
|
||||
break;
|
||||
}
|
||||
goto ResolveComponent;
|
||||
case Component comp:
|
||||
case GameObject g:
|
||||
ResolveComponent:
|
||||
reg.path = "/nodes/" + id + "/" + reg.propertyBinding;
|
||||
var componentPath = reg.path;
|
||||
|
||||
var anyOtherResolverWasAbleToResolve = false;
|
||||
foreach (var res in exporter.pointerResolvers)
|
||||
{
|
||||
if (res.TryResolve(reg.animatedObject, ref componentPath))
|
||||
{
|
||||
reg.path = componentPath;
|
||||
anyOtherResolverWasAbleToResolve = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (exporter.pointerResolvers.Count > 0 && !anyOtherResolverWasAbleToResolve)
|
||||
{
|
||||
// we don't need to warn for regular transforms that are not RectTransforms,
|
||||
// but we want to warn for everything else that may be animated.
|
||||
if (!(reg.animatedObject is Transform && !(reg.animatedObject is RectTransform)))
|
||||
Debug.LogWarning("Wasn't able to resolve animation pointer for " + reg.animatedObject + " at " + componentPath + ". You can attach custom resolvers to animate properties in extensions.", reg.animatedObject as Object);
|
||||
}
|
||||
else if (!anyOtherResolverWasAbleToResolve)
|
||||
{
|
||||
// we don't need to warn for regular transforms that are not RectTransforms,
|
||||
// but we want to warn for everything else that may be animated.
|
||||
if (!(reg.animatedObject is Transform && !(reg.animatedObject is RectTransform)))
|
||||
Debug.LogWarning("Wasn't able to resolve animation pointer for " + reg.animatedObject + " at " + componentPath + ". You can attach custom resolvers to animate properties in extensions.", reg.animatedObject as Object);
|
||||
}
|
||||
break;
|
||||
case Material mat:
|
||||
reg.path = "/materials/" + id + "/" + reg.propertyBinding;
|
||||
break;
|
||||
}
|
||||
animationPointerResolverMarker.End();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 23086a9473b049b3ab8e64001d13a28b
|
||||
timeCreated: 1648544951
|
||||
@@ -0,0 +1,201 @@
|
||||
using System.Collections.Generic;
|
||||
using GLTF.Schema;
|
||||
using UnityEngine;
|
||||
using UnityGLTF.Extensions;
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public static class MaterialExtensions
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
[InitializeOnLoadMethod]
|
||||
#endif
|
||||
[RuntimeInitializeOnLoadMethod]
|
||||
static void InitExt()
|
||||
{
|
||||
GLTFSceneExporter.AfterMaterialExport += GLTFSceneExporterOnAfterMaterialExport;
|
||||
}
|
||||
|
||||
private static readonly int thicknessTexture = Shader.PropertyToID("thicknessTexture");
|
||||
private static readonly int thicknessFactor = Shader.PropertyToID("thicknessFactor");
|
||||
private static readonly int attenuationDistance = Shader.PropertyToID("attenuationDistance");
|
||||
private static readonly int attenuationColor = Shader.PropertyToID("attenuationColor");
|
||||
private static readonly int ior = Shader.PropertyToID("ior");
|
||||
private static readonly int transmissionFactor = Shader.PropertyToID("transmissionFactor");
|
||||
private static readonly int transmissionTexture = Shader.PropertyToID("transmissionTexture");
|
||||
|
||||
private static readonly int iridescenceFactor = Shader.PropertyToID("iridescenceFactor");
|
||||
private static readonly int iridescenceIor = Shader.PropertyToID("iridescenceIor");
|
||||
private static readonly int iridescenceThicknessMinimum = Shader.PropertyToID("iridescenceThicknessMinimum");
|
||||
private static readonly int iridescenceThicknessMaximum = Shader.PropertyToID("iridescenceThicknessMaximum");
|
||||
private static readonly int iridescenceTexture = Shader.PropertyToID("iridescenceTexture");
|
||||
private static readonly int iridescenceThicknessTexture = Shader.PropertyToID("iridescenceThicknessTexture");
|
||||
|
||||
private static readonly int specularFactor = Shader.PropertyToID("specularFactor");
|
||||
private static readonly int specularColorFactor = Shader.PropertyToID("specularColorFactor");
|
||||
private static readonly int specularTexture = Shader.PropertyToID("specularTexture");
|
||||
private static readonly int specularColorTexture = Shader.PropertyToID("specularColorTexture");
|
||||
|
||||
private static readonly int clearcoatFactor = Shader.PropertyToID("clearcoatFactor");
|
||||
private static readonly int clearcoatTexture = Shader.PropertyToID("clearcoatTexture");
|
||||
private static readonly int clearcoatRoughnessFactor = Shader.PropertyToID("clearcoatRoughnessFactor");
|
||||
private static readonly int clearcoatRoughnessTexture = Shader.PropertyToID("clearcoatRoughnessTexture");
|
||||
private static readonly int clearcoatNormalTexture = Shader.PropertyToID("clearcoatNormalTexture");
|
||||
|
||||
|
||||
private static void GLTFSceneExporterOnAfterMaterialExport(GLTFSceneExporter exporter, GLTFRoot gltfroot, Material material, GLTFMaterial materialnode)
|
||||
{
|
||||
if (!material) return;
|
||||
|
||||
var usesTransmission = material.IsKeywordEnabled("_VOLUME_TRANSMISSION_ON");
|
||||
var usesVolume = material.HasProperty("_VOLUME_ON") && material.GetFloat("_VOLUME_ON") > 0.5f;
|
||||
var hasIor = material.HasProperty(ior) && !Mathf.Approximately(material.GetFloat(ior), KHR_materials_ior.DefaultIor);
|
||||
|
||||
if (hasIor)
|
||||
{
|
||||
if (materialnode.Extensions == null)
|
||||
materialnode.Extensions = new Dictionary<string, IExtension>();
|
||||
|
||||
var vi = new KHR_materials_ior();
|
||||
if (materialnode.Extensions.TryGetValue(KHR_materials_ior_Factory.EXTENSION_NAME, out var vv1))
|
||||
vi = (KHR_materials_ior) vv1;
|
||||
else
|
||||
materialnode.Extensions.Add(KHR_materials_ior_Factory.EXTENSION_NAME, vi);
|
||||
|
||||
exporter.DeclareExtensionUsage(KHR_materials_ior_Factory.EXTENSION_NAME, false);
|
||||
|
||||
if (material.HasProperty(ior))
|
||||
vi.ior = material.GetFloat(ior);
|
||||
}
|
||||
|
||||
if (usesTransmission)
|
||||
{
|
||||
if (materialnode.Extensions == null)
|
||||
materialnode.Extensions = new Dictionary<string, IExtension>();
|
||||
|
||||
exporter.DeclareExtensionUsage(KHR_materials_transmission_Factory.EXTENSION_NAME, false);
|
||||
|
||||
// if the material already has an extension, we should get and modify that
|
||||
var vt = new KHR_materials_transmission();
|
||||
|
||||
if (materialnode.Extensions.TryGetValue(KHR_materials_transmission_Factory.EXTENSION_NAME, out var vv2))
|
||||
vt = (KHR_materials_transmission) vv2;
|
||||
else
|
||||
materialnode.Extensions.Add(KHR_materials_transmission_Factory.EXTENSION_NAME, vt);
|
||||
|
||||
if (material.HasProperty(transmissionFactor))
|
||||
vt.transmissionFactor = material.GetFloat(transmissionFactor);
|
||||
if (material.HasProperty(transmissionTexture) && material.GetTexture(transmissionTexture))
|
||||
vt.transmissionTexture = exporter.ExportTextureInfo(material.GetTexture(transmissionTexture), nameof(transmissionTexture));
|
||||
}
|
||||
|
||||
if (usesVolume)
|
||||
{
|
||||
if (materialnode.Extensions == null)
|
||||
materialnode.Extensions = new Dictionary<string, IExtension>();
|
||||
|
||||
exporter.DeclareExtensionUsage(KHR_materials_volume_Factory.EXTENSION_NAME, false);
|
||||
|
||||
// if the material already has an extension, we should get and modify that
|
||||
var ve = new KHR_materials_volume();
|
||||
|
||||
if (materialnode.Extensions.TryGetValue(KHR_materials_volume_Factory.EXTENSION_NAME, out var vv0))
|
||||
ve = (KHR_materials_volume)vv0;
|
||||
else
|
||||
materialnode.Extensions.Add(KHR_materials_volume_Factory.EXTENSION_NAME, ve);
|
||||
|
||||
if (material.HasProperty(thicknessFactor))
|
||||
ve.thicknessFactor = material.GetFloat(thicknessFactor);
|
||||
if (material.HasProperty(thicknessTexture) && material.GetTexture(thicknessTexture))
|
||||
ve.thicknessTexture = exporter.ExportTextureInfo(material.GetTexture(thicknessTexture), nameof(thicknessTexture));
|
||||
if (material.HasProperty(attenuationDistance))
|
||||
ve.attenuationDistance = material.GetFloat(attenuationDistance);
|
||||
if (material.HasProperty(attenuationColor))
|
||||
ve.attenuationColor = material.GetColor(attenuationColor).ToNumericsColorRaw();
|
||||
}
|
||||
|
||||
if (material.IsKeywordEnabled("_IRIDESCENCE_ON"))
|
||||
{
|
||||
exporter.DeclareExtensionUsage(KHR_materials_iridescence_Factory.EXTENSION_NAME, false);
|
||||
|
||||
if (materialnode.Extensions == null)
|
||||
materialnode.Extensions = new Dictionary<string, IExtension>();
|
||||
|
||||
var vir = new KHR_materials_iridescence();
|
||||
|
||||
if (materialnode.Extensions.TryGetValue(KHR_materials_iridescence_Factory.EXTENSION_NAME, out var vv0))
|
||||
vir = (KHR_materials_iridescence) vv0;
|
||||
else
|
||||
materialnode.Extensions.Add(KHR_materials_iridescence_Factory.EXTENSION_NAME, vir);
|
||||
|
||||
if (material.HasProperty(iridescenceFactor))
|
||||
vir.iridescenceFactor = material.GetFloat(iridescenceFactor);
|
||||
if (material.HasProperty(iridescenceIor))
|
||||
vir.iridescenceIor = material.GetFloat(iridescenceIor);
|
||||
if (material.HasProperty(iridescenceThicknessMinimum))
|
||||
vir.iridescenceThicknessMinimum = material.GetFloat(iridescenceThicknessMinimum);
|
||||
if (material.HasProperty(iridescenceThicknessMaximum))
|
||||
vir.iridescenceThicknessMaximum = material.GetFloat(iridescenceThicknessMaximum);
|
||||
if (material.HasProperty(iridescenceTexture) && material.GetTexture(iridescenceTexture))
|
||||
vir.iridescenceTexture = exporter.ExportTextureInfo(material.GetTexture(iridescenceTexture), nameof(iridescenceTexture));
|
||||
if (material.HasProperty(iridescenceThicknessTexture) && material.GetTexture(iridescenceThicknessTexture))
|
||||
vir.iridescenceThicknessTexture = exporter.ExportTextureInfo(material.GetTexture(iridescenceThicknessTexture), nameof(iridescenceThicknessTexture));
|
||||
}
|
||||
|
||||
if (material.IsKeywordEnabled("_SPECULAR_ON"))
|
||||
{
|
||||
exporter.DeclareExtensionUsage(KHR_materials_specular_Factory.EXTENSION_NAME, false);
|
||||
|
||||
if (materialnode.Extensions == null)
|
||||
materialnode.Extensions = new Dictionary<string, IExtension>();
|
||||
|
||||
var vir = new KHR_materials_specular();
|
||||
|
||||
if (materialnode.Extensions.TryGetValue(KHR_materials_specular_Factory.EXTENSION_NAME, out var vv0))
|
||||
vir = (KHR_materials_specular) vv0;
|
||||
else
|
||||
materialnode.Extensions.Add(KHR_materials_specular_Factory.EXTENSION_NAME, vir);
|
||||
|
||||
if (material.HasProperty(specularFactor))
|
||||
vir.specularFactor = material.GetFloat(specularFactor);
|
||||
if (material.HasProperty(specularColorFactor))
|
||||
vir.specularColorFactor = material.GetColor(specularColorFactor).ToNumericsColorRaw();
|
||||
if (material.HasProperty(specularTexture) && material.GetTexture(specularTexture))
|
||||
vir.specularTexture = exporter.ExportTextureInfo(material.GetTexture(specularTexture), nameof(specularTexture));
|
||||
if (material.HasProperty(specularColorTexture) && material.GetTexture(specularColorTexture))
|
||||
vir.specularColorTexture = exporter.ExportTextureInfo(material.GetTexture(specularColorTexture), nameof(specularColorTexture));
|
||||
}
|
||||
|
||||
if (material.IsKeywordEnabled("_CLEARCOAT_ON"))
|
||||
{
|
||||
exporter.DeclareExtensionUsage(KHR_materials_clearcoat_Factory.EXTENSION_NAME, false);
|
||||
|
||||
if (materialnode.Extensions == null)
|
||||
materialnode.Extensions = new Dictionary<string, IExtension>();
|
||||
|
||||
var cc = new KHR_materials_clearcoat();
|
||||
|
||||
if (materialnode.Extensions.TryGetValue(KHR_materials_clearcoat_Factory.EXTENSION_NAME, out var vv0))
|
||||
cc = (KHR_materials_clearcoat) vv0;
|
||||
else
|
||||
materialnode.Extensions.Add(KHR_materials_clearcoat_Factory.EXTENSION_NAME, cc);
|
||||
|
||||
if (material.HasProperty(clearcoatFactor))
|
||||
cc.clearcoatFactor = material.GetFloat(clearcoatFactor);
|
||||
if (material.HasProperty(clearcoatTexture))
|
||||
cc.clearcoatTexture = exporter.ExportTextureInfo(material.GetTexture(clearcoatTexture), nameof(clearcoatTexture));
|
||||
if (material.HasProperty(clearcoatRoughnessFactor))
|
||||
cc.clearcoatRoughnessFactor = material.GetFloat(clearcoatRoughnessFactor);
|
||||
if (material.HasProperty(clearcoatRoughnessTexture))
|
||||
cc.clearcoatRoughnessTexture = exporter.ExportTextureInfo(material.GetTexture(clearcoatRoughnessTexture), nameof(clearcoatRoughnessTexture));
|
||||
if (material.HasProperty(clearcoatNormalTexture))
|
||||
cc.clearcoatNormalTexture = exporter.ExportTextureInfo(material.GetTexture(clearcoatNormalTexture), nameof(clearcoatNormalTexture));
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5152940c6ada2f3449baca5def38ea64
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,606 @@
|
||||
using GLTF;
|
||||
using GLTF.Schema;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF.Extensions
|
||||
{
|
||||
public static class SchemaExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Define the transformation between Unity coordinate space and glTF.
|
||||
/// glTF is a right-handed coordinate system, where the 'right' direction is -X relative to
|
||||
/// Unity's coordinate system.
|
||||
/// glTF matrix: column vectors, column-major storage, +Y up, +Z forward, -X right, right-handed
|
||||
/// unity matrix: column vectors, column-major storage, +Y up, +Z forward, +X right, left-handed
|
||||
/// multiply by a negative X scale to convert handedness
|
||||
/// </summary>
|
||||
public static readonly GLTF.Math.Vector3 CoordinateSpaceConversionScale = new GLTF.Math.Vector3(-1, 1, 1);
|
||||
|
||||
/// <summary>
|
||||
/// Define whether the coordinate space scale conversion above means we have a change in handedness.
|
||||
/// This is used when determining the conventional direction of rotation - the right-hand rule states
|
||||
/// that rotations are clockwise in left-handed systems and counter-clockwise in right-handed systems.
|
||||
/// Reversing the direction of one or three axes of reverses the handedness.
|
||||
/// </summary>
|
||||
public static bool CoordinateSpaceConversionRequiresHandednessFlip
|
||||
{
|
||||
get
|
||||
{
|
||||
return CoordinateSpaceConversionScale.X * CoordinateSpaceConversionScale.Y * CoordinateSpaceConversionScale.Z < 0.0f;
|
||||
}
|
||||
}
|
||||
|
||||
public static readonly GLTF.Math.Vector4 TangentSpaceConversionScale = new GLTF.Math.Vector4(-1, 1, 1, -1);
|
||||
|
||||
/// <summary>
|
||||
/// Get the converted unity translation, rotation, and scale from a gltf node
|
||||
/// </summary>
|
||||
/// <param name="node">gltf node</param>
|
||||
/// <param name="position">unity translation vector</param>
|
||||
/// <param name="rotation">unity rotation quaternion</param>
|
||||
/// <param name="scale">unity scale vector</param>
|
||||
public static void GetUnityTRSProperties(this Node node, out Vector3 position, out Quaternion rotation,
|
||||
out Vector3 scale)
|
||||
{
|
||||
if (!node.UseTRS)
|
||||
{
|
||||
Matrix4x4 unityMat = node.Matrix.ToUnityMatrix4x4Convert();
|
||||
unityMat.GetTRSProperties(out position, out rotation, out scale);
|
||||
}
|
||||
else
|
||||
{
|
||||
position = node.Translation.ToUnityVector3Convert();
|
||||
rotation = node.Rotation.ToUnityQuaternionConvert();
|
||||
scale = node.Scale.ToUnityVector3Raw();
|
||||
}
|
||||
}
|
||||
|
||||
internal static readonly Quaternion InvertDirection = new Quaternion(0, -1, 0, 0);
|
||||
|
||||
/// <summary>
|
||||
/// Set a gltf node's converted translation, rotation, and scale from a unity transform
|
||||
/// </summary>
|
||||
/// <param name="node">gltf node to modify</param>
|
||||
/// <param name="transform">unity transform to convert</param>
|
||||
/// <param name="invertLookDirection">invert look direction (e.g. for lights and cameras)</param>
|
||||
public static void SetUnityTransform(this Node node, Transform transform, bool invertLookDirection)
|
||||
{
|
||||
node.Translation = transform.localPosition.ToGltfVector3Convert();
|
||||
node.Rotation = (transform.localRotation * (invertLookDirection ? InvertDirection : Quaternion.identity)).ToGltfQuaternionConvert();
|
||||
node.Scale = transform.localScale.ToGltfVector3Raw();
|
||||
}
|
||||
|
||||
// todo: move to utility class
|
||||
/// <summary>
|
||||
/// Get unity translation, rotation, and scale from a unity matrix
|
||||
/// </summary>
|
||||
/// <param name="mat">unity matrix to get properties from</param>
|
||||
/// <param name="position">unity translation vector</param>
|
||||
/// <param name="rotation">unity rotation quaternion</param>
|
||||
/// <param name="scale">unity scale vector</param>
|
||||
public static void GetTRSProperties(this Matrix4x4 mat, out Vector3 position, out Quaternion rotation,
|
||||
out Vector3 scale)
|
||||
{
|
||||
position = mat.GetColumn(3);
|
||||
|
||||
Vector3 x = mat.GetColumn(0);
|
||||
Vector3 y = mat.GetColumn(1);
|
||||
Vector3 z = mat.GetColumn(2);
|
||||
Vector3 calculatedZ = Vector3.Cross(x, y);
|
||||
bool mirrored = Vector3.Dot(calculatedZ, z) < 0.0f;
|
||||
|
||||
scale = new Vector3(x.magnitude * (mirrored ? -1.0f : 1.0f), y.magnitude, z.magnitude);
|
||||
|
||||
rotation = Quaternion.LookRotation(mat.GetColumn(2), mat.GetColumn(1));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get converted unity translation, rotation, and scale from a gltf matrix
|
||||
/// </summary>
|
||||
/// <param name="gltfMat">gltf matrix to get and convert properties from</param>
|
||||
/// <param name="position">unity translation vector</param>
|
||||
/// <param name="rotation">unity rotation quaternion</param>
|
||||
/// <param name="scale">unity scale vector</param>
|
||||
public static void GetTRSProperties(this GLTF.Math.Matrix4x4 gltfMat, out Vector3 position, out Quaternion rotation,
|
||||
out Vector3 scale)
|
||||
{
|
||||
gltfMat.ToUnityMatrix4x4Convert().GetTRSProperties(out position, out rotation, out scale);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get a gltf column vector from a gltf matrix
|
||||
/// </summary>
|
||||
/// <param name="mat">gltf matrix</param>
|
||||
/// <param name="columnNum">the specified column vector from the matrix</param>
|
||||
/// <returns></returns>
|
||||
public static GLTF.Math.Vector4 GetColumn(this GLTF.Math.Matrix4x4 mat, uint columnNum)
|
||||
{
|
||||
switch (columnNum)
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
return new GLTF.Math.Vector4(mat.M11, mat.M21, mat.M31, mat.M41);
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
return new GLTF.Math.Vector4(mat.M12, mat.M22, mat.M32, mat.M42);
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
return new GLTF.Math.Vector4(mat.M13, mat.M23, mat.M33, mat.M43);
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
return new GLTF.Math.Vector4(mat.M14, mat.M24, mat.M34, mat.M44);
|
||||
}
|
||||
default:
|
||||
throw new System.Exception("column num is out of bounds");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert gltf quaternion to a unity quaternion
|
||||
/// </summary>
|
||||
/// <param name="gltfQuat">gltf quaternion</param>
|
||||
/// <returns>unity quaternion</returns>
|
||||
public static Quaternion ToUnityQuaternionConvert(this GLTF.Math.Quaternion gltfQuat)
|
||||
{
|
||||
Vector3 fromAxisOfRotation = new Vector3(gltfQuat.X, gltfQuat.Y, gltfQuat.Z);
|
||||
float axisFlipScale = CoordinateSpaceConversionRequiresHandednessFlip ? -1.0f : 1.0f;
|
||||
Vector3 toAxisOfRotation = axisFlipScale * Vector3.Scale(fromAxisOfRotation, CoordinateSpaceConversionScale.ToUnityVector3Raw());
|
||||
|
||||
return new Quaternion(toAxisOfRotation.x, toAxisOfRotation.y, toAxisOfRotation.z, gltfQuat.W);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert unity quaternion to a gltf quaternion
|
||||
/// </summary>
|
||||
/// <param name="unityQuat">unity quaternion</param>
|
||||
/// <returns>gltf quaternion</returns>
|
||||
public static GLTF.Math.Quaternion ToGltfQuaternionConvert(this Quaternion unityQuat)
|
||||
{
|
||||
Vector3 fromAxisOfRotation = new Vector3(unityQuat.x, unityQuat.y, unityQuat.z);
|
||||
float axisFlipScale = CoordinateSpaceConversionRequiresHandednessFlip ? -1.0f : 1.0f;
|
||||
Vector3 toAxisOfRotation = axisFlipScale * Vector3.Scale(fromAxisOfRotation, CoordinateSpaceConversionScale.ToUnityVector3Raw());
|
||||
|
||||
return new GLTF.Math.Quaternion(toAxisOfRotation.x, toAxisOfRotation.y, toAxisOfRotation.z, unityQuat.w);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert gltf matrix to a unity matrix
|
||||
/// </summary>
|
||||
/// <param name="gltfMat">gltf matrix</param>
|
||||
/// <returns>unity matrix</returns>
|
||||
public static Matrix4x4 ToUnityMatrix4x4Convert(this GLTF.Math.Matrix4x4 gltfMat)
|
||||
{
|
||||
Matrix4x4 rawUnityMat = gltfMat.ToUnityMatrix4x4Raw();
|
||||
Vector3 coordinateSpaceConversionScale = CoordinateSpaceConversionScale.ToUnityVector3Raw();
|
||||
Matrix4x4 convert = Matrix4x4.Scale(coordinateSpaceConversionScale);
|
||||
Matrix4x4 unityMat = convert * rawUnityMat * convert;
|
||||
return unityMat;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert gltf matrix to a unity matrix
|
||||
/// </summary>
|
||||
/// <param name="unityMat">unity matrix</param>
|
||||
/// <returns>gltf matrix</returns>
|
||||
public static GLTF.Math.Matrix4x4 ToGltfMatrix4x4Convert(this Matrix4x4 unityMat)
|
||||
{
|
||||
Vector3 coordinateSpaceConversionScale = CoordinateSpaceConversionScale.ToUnityVector3Raw();
|
||||
Matrix4x4 convert = Matrix4x4.Scale(coordinateSpaceConversionScale);
|
||||
GLTF.Math.Matrix4x4 gltfMat = (convert * unityMat * convert).ToGltfMatrix4x4Raw();
|
||||
return gltfMat;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert gltf Vector3 to unity Vector3
|
||||
/// </summary>
|
||||
/// <param name="gltfVec3">gltf vector3</param>
|
||||
/// <returns>unity vector3</returns>
|
||||
public static Vector3 ToUnityVector3Convert(this GLTF.Math.Vector3 gltfVec3)
|
||||
{
|
||||
Vector3 coordinateSpaceConversionScale = CoordinateSpaceConversionScale.ToUnityVector3Raw();
|
||||
Vector3 unityVec3 = Vector3.Scale(gltfVec3.ToUnityVector3Raw(), coordinateSpaceConversionScale);
|
||||
return unityVec3;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert unity Vector3 to gltf Vector3
|
||||
/// </summary>
|
||||
/// <param name="unityVec3">unity Vector3</param>
|
||||
/// <returns>gltf Vector3</returns>
|
||||
public static GLTF.Math.Vector3 ToGltfVector3Convert(this Vector3 unityVec3)
|
||||
{
|
||||
Vector3 coordinateSpaceConversionScale = CoordinateSpaceConversionScale.ToUnityVector3Raw();
|
||||
GLTF.Math.Vector3 gltfVec3 = Vector3.Scale(unityVec3, coordinateSpaceConversionScale).ToGltfVector3Raw();
|
||||
return gltfVec3;
|
||||
}
|
||||
|
||||
public static GLTF.Math.Vector3 ToGltfVector3Raw(this Vector3 unityVec3)
|
||||
{
|
||||
GLTF.Math.Vector3 gltfVec3 = new GLTF.Math.Vector3(unityVec3.x, unityVec3.y, unityVec3.z);
|
||||
return gltfVec3;
|
||||
}
|
||||
|
||||
public static GLTF.Math.Vector4 ToGltfVector4Raw(this Vector4 unityVec4)
|
||||
{
|
||||
GLTF.Math.Vector4 gltfVec4 = new GLTF.Math.Vector4(unityVec4.x, unityVec4.y, unityVec4.z, unityVec4.w);
|
||||
return gltfVec4;
|
||||
}
|
||||
|
||||
public static Matrix4x4 ToUnityMatrix4x4Raw(this GLTF.Math.Matrix4x4 gltfMat)
|
||||
{
|
||||
Vector4 rawUnityCol0 = gltfMat.GetColumn(0).ToUnityVector4Raw();
|
||||
Vector4 rawUnityCol1 = gltfMat.GetColumn(1).ToUnityVector4Raw();
|
||||
Vector4 rawUnityCol2 = gltfMat.GetColumn(2).ToUnityVector4Raw();
|
||||
Vector4 rawUnityCol3 = gltfMat.GetColumn(3).ToUnityVector4Raw();
|
||||
Matrix4x4 rawUnityMat = new UnityEngine.Matrix4x4();
|
||||
rawUnityMat.SetColumn(0, rawUnityCol0);
|
||||
rawUnityMat.SetColumn(1, rawUnityCol1);
|
||||
rawUnityMat.SetColumn(2, rawUnityCol2);
|
||||
rawUnityMat.SetColumn(3, rawUnityCol3);
|
||||
|
||||
return rawUnityMat;
|
||||
}
|
||||
|
||||
public static GLTF.Math.Matrix4x4 ToGltfMatrix4x4Raw(this Matrix4x4 unityMat)
|
||||
{
|
||||
GLTF.Math.Vector4 c0 = unityMat.GetColumn(0).ToGltfVector4Raw();
|
||||
GLTF.Math.Vector4 c1 = unityMat.GetColumn(1).ToGltfVector4Raw();
|
||||
GLTF.Math.Vector4 c2 = unityMat.GetColumn(2).ToGltfVector4Raw();
|
||||
GLTF.Math.Vector4 c3 = unityMat.GetColumn(3).ToGltfVector4Raw();
|
||||
GLTF.Math.Matrix4x4 rawGltfMat = new GLTF.Math.Matrix4x4(c0.X, c0.Y, c0.Z, c0.W, c1.X, c1.Y, c1.Z, c1.W, c2.X, c2.Y, c2.Z, c2.W, c3.X, c3.Y, c3.Z, c3.W);
|
||||
return rawGltfMat;
|
||||
}
|
||||
|
||||
public static Vector2 ToUnityVector2Raw(this GLTF.Math.Vector2 vec2)
|
||||
{
|
||||
return new Vector2(vec2.X, vec2.Y);
|
||||
}
|
||||
|
||||
public static Vector2[] ToUnityVector2Raw(this GLTF.Math.Vector2[] inVecArr)
|
||||
{
|
||||
Vector2[] outVecArr = new Vector2[inVecArr.Length];
|
||||
for (int i = 0; i < inVecArr.Length; ++i)
|
||||
{
|
||||
outVecArr[i] = inVecArr[i].ToUnityVector2Raw();
|
||||
}
|
||||
return outVecArr;
|
||||
}
|
||||
|
||||
public static void ToUnityVector2Raw(this GLTF.Math.Vector2[] inArr, Vector2[] outArr, int offset = 0)
|
||||
{
|
||||
for (int i = 0; i < inArr.Length; i++)
|
||||
{
|
||||
outArr[offset + i] = inArr[i].ToUnityVector2Raw();
|
||||
}
|
||||
}
|
||||
|
||||
public static Vector3 ToUnityVector3Raw(this GLTF.Math.Vector3 vec3)
|
||||
{
|
||||
return new Vector3(vec3.X, vec3.Y, vec3.Z);
|
||||
}
|
||||
|
||||
public static Vector3[] ToUnityVector3Raw(this GLTF.Math.Vector3[] inVecArr)
|
||||
{
|
||||
Vector3[] outVecArr = new Vector3[inVecArr.Length];
|
||||
for (int i = 0; i < inVecArr.Length; ++i)
|
||||
{
|
||||
outVecArr[i] = inVecArr[i].ToUnityVector3Raw();
|
||||
}
|
||||
return outVecArr;
|
||||
}
|
||||
|
||||
public static void ToUnityVector3Raw(this GLTF.Math.Vector3[] inArr, Vector3[] outArr, int offset = 0)
|
||||
{
|
||||
for (int i = 0; i < inArr.Length; i++)
|
||||
{
|
||||
outArr[offset + i] = inArr[i].ToUnityVector3Raw();
|
||||
}
|
||||
}
|
||||
|
||||
public static Vector4 ToUnityVector4Raw(this GLTF.Math.Vector4 vec4)
|
||||
{
|
||||
return new Vector4(vec4.X, vec4.Y, vec4.Z, vec4.W);
|
||||
}
|
||||
|
||||
public static Vector4[] ToUnityVector4Raw(this GLTF.Math.Vector4[] inVecArr)
|
||||
{
|
||||
Vector4[] outVecArr = new Vector4[inVecArr.Length];
|
||||
for (int i = 0; i < inVecArr.Length; ++i)
|
||||
{
|
||||
outVecArr[i] = inVecArr[i].ToUnityVector4Raw();
|
||||
}
|
||||
return outVecArr;
|
||||
}
|
||||
|
||||
public static void ToUnityVector4Raw(this GLTF.Math.Vector4[] inArr, Vector4[] outArr, int offset = 0)
|
||||
{
|
||||
for (int i = 0; i < inArr.Length; i++)
|
||||
{
|
||||
outArr[offset + i] = inArr[i].ToUnityVector4Raw();
|
||||
}
|
||||
}
|
||||
|
||||
public static UnityEngine.Color ToUnityColorRaw(this GLTF.Math.Color color)
|
||||
{
|
||||
var c = new UnityEngine.Color(color.R, color.G, color.B, color.A).gamma;
|
||||
return c;
|
||||
}
|
||||
|
||||
public static UnityEngine.Color ToUnityColorLinear(this GLTF.Math.Color color)
|
||||
{
|
||||
var c = new UnityEngine.Color(color.R, color.G, color.B, color.A);
|
||||
return c;
|
||||
}
|
||||
|
||||
public static GLTF.Math.Color ToNumericsColorRaw(this UnityEngine.Color color)
|
||||
{
|
||||
var c = color;
|
||||
return new GLTF.Math.Color(c.r, c.g, c.b, c.a);
|
||||
}
|
||||
|
||||
public static GLTF.Math.Color ToNumericsColorLinear(this UnityEngine.Color color)
|
||||
{
|
||||
var lc = color.linear;
|
||||
return new GLTF.Math.Color(lc.r, lc.g, lc.b, lc.a);
|
||||
}
|
||||
|
||||
public static GLTF.Math.Color[] ToNumericsColorLinear(this UnityEngine.Color[] inColorArr)
|
||||
{
|
||||
GLTF.Math.Color[] outColorArr = new GLTF.Math.Color[inColorArr.Length];
|
||||
for (int i = 0; i < inColorArr.Length; ++i)
|
||||
{
|
||||
outColorArr[i] = inColorArr[i].ToNumericsColorLinear();
|
||||
}
|
||||
return outColorArr;
|
||||
}
|
||||
|
||||
public static UnityEngine.Color[] ToUnityColorRaw(this GLTF.Math.Color[] inColorArr)
|
||||
{
|
||||
UnityEngine.Color[] outColorArr = new UnityEngine.Color[inColorArr.Length];
|
||||
for (int i = 0; i < inColorArr.Length; ++i)
|
||||
{
|
||||
outColorArr[i] = inColorArr[i].ToUnityColorRaw();
|
||||
}
|
||||
return outColorArr;
|
||||
}
|
||||
|
||||
public static UnityEngine.Color[] ToLinear(this UnityEngine.Color[] inColorArr)
|
||||
{
|
||||
UnityEngine.Color[] outColorArr = new UnityEngine.Color[inColorArr.Length];
|
||||
for (int i = 0; i < inColorArr.Length; ++i)
|
||||
{
|
||||
outColorArr[i] = inColorArr[i].linear;
|
||||
}
|
||||
return outColorArr;
|
||||
}
|
||||
|
||||
public static void ToUnityColorRaw(this GLTF.Math.Color[] inArr, Color[] outArr, int offset = 0)
|
||||
{
|
||||
for (int i = 0; i < inArr.Length; i++)
|
||||
{
|
||||
outArr[offset + i] = inArr[i].ToUnityColorRaw();
|
||||
}
|
||||
}
|
||||
|
||||
public static void ToUnityColorLinear(this GLTF.Math.Color[] inArr, Color[] outArr, int offset = 0)
|
||||
{
|
||||
for (int i = 0; i < inArr.Length; i++)
|
||||
{
|
||||
outArr[offset + i] = inArr[i].ToUnityColorLinear();
|
||||
}
|
||||
}
|
||||
|
||||
public static int[] ToIntArrayRaw(this uint[] uintArr)
|
||||
{
|
||||
int[] intArr = new int[uintArr.Length];
|
||||
for (int i = 0; i < uintArr.Length; ++i)
|
||||
{
|
||||
uint uintVal = uintArr[i];
|
||||
Debug.Assert(uintVal <= int.MaxValue);
|
||||
intArr[i] = (int)uintVal;
|
||||
}
|
||||
|
||||
return intArr;
|
||||
}
|
||||
|
||||
public static GLTF.Math.Quaternion ToGltfQuaternionRaw(this Quaternion unityQuat)
|
||||
{
|
||||
return new GLTF.Math.Quaternion(unityQuat.x, unityQuat.y, unityQuat.z, unityQuat.w);
|
||||
}
|
||||
|
||||
public static Quaternion ToUnityQuaternionRaw(this GLTF.Math.Quaternion quaternion)
|
||||
{
|
||||
return new Quaternion(quaternion.X, quaternion.Y, quaternion.Z, quaternion.W);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Flips the V component of the UV (1-V) to put from glTF into Unity space
|
||||
/// </summary>
|
||||
/// <param name="attributeAccessor">The attribute accessor to modify</param>
|
||||
public static void FlipTexCoordArrayV(ref AttributeAccessor attributeAccessor)
|
||||
{
|
||||
for (var i = 0; i < attributeAccessor.AccessorContent.AsVec2s.Length; i++)
|
||||
{
|
||||
attributeAccessor.AccessorContent.AsVec2s[i].Y = 1.0f - attributeAccessor.AccessorContent.AsVec2s[i].Y;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Flip the V component of the UV (1-V)
|
||||
/// </summary>
|
||||
/// <param name="array">The array to copy from and modify</param>
|
||||
/// <returns>Copied Vector2 with coordinates in glTF space</returns>
|
||||
public static UnityEngine.Vector2[] FlipTexCoordArrayVAndCopy(UnityEngine.Vector2[] array)
|
||||
{
|
||||
var returnArray = new UnityEngine.Vector2[array.Length];
|
||||
|
||||
for (var i = 0; i < array.Length; i++)
|
||||
{
|
||||
returnArray[i].x = array[i].x;
|
||||
returnArray[i].y = 1.0f - array[i].y;
|
||||
}
|
||||
|
||||
return returnArray;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts vector3 to specified coordinate space
|
||||
/// </summary>
|
||||
/// <param name="attributeAccessor">The attribute accessor to modify</param>
|
||||
/// <param name="coordinateSpaceCoordinateScale">The coordinate space to move into</param>
|
||||
public static void ConvertVector3CoordinateSpace(ref AttributeAccessor attributeAccessor, GLTF.Math.Vector3 coordinateSpaceCoordinateScale)
|
||||
{
|
||||
for (int i = 0; i < attributeAccessor.AccessorContent.AsVertices.Length; i++)
|
||||
{
|
||||
attributeAccessor.AccessorContent.AsVertices[i].X *= coordinateSpaceCoordinateScale.X;
|
||||
attributeAccessor.AccessorContent.AsVertices[i].Y *= coordinateSpaceCoordinateScale.Y;
|
||||
attributeAccessor.AccessorContent.AsVertices[i].Z *= coordinateSpaceCoordinateScale.Z;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts and copies based on the specified coordinate scale
|
||||
/// </summary>
|
||||
/// <param name="array">The array to convert and copy</param>
|
||||
/// <param name="coordinateSpaceCoordinateScale">The specified coordinate space</param>
|
||||
/// <returns>The copied and converted coordinate space</returns>
|
||||
public static UnityEngine.Vector3[] ConvertVector3CoordinateSpaceAndCopy(Vector3[] array, GLTF.Math.Vector3 coordinateSpaceCoordinateScale)
|
||||
{
|
||||
var returnArray = new UnityEngine.Vector3[array.Length];
|
||||
var coordinateScale = coordinateSpaceCoordinateScale.ToUnityVector3Raw();
|
||||
|
||||
for (int i = 0; i < array.Length; i++)
|
||||
{
|
||||
returnArray[i] = array[i];
|
||||
returnArray[i].Scale(coordinateScale);
|
||||
}
|
||||
|
||||
return returnArray;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts vector4 to specified coordinate space
|
||||
/// </summary>
|
||||
/// <param name="attributeAccessor">The attribute accessor to modify</param>
|
||||
/// <param name="coordinateSpaceCoordinateScale">The coordinate space to move into</param>
|
||||
public static void ConvertVector4CoordinateSpace(ref AttributeAccessor attributeAccessor, GLTF.Math.Vector4 coordinateSpaceCoordinateScale)
|
||||
{
|
||||
for (int i = 0; i < attributeAccessor.AccessorContent.AsVec4s.Length; i++)
|
||||
{
|
||||
attributeAccessor.AccessorContent.AsVec4s[i].X *= coordinateSpaceCoordinateScale.X;
|
||||
attributeAccessor.AccessorContent.AsVec4s[i].Y *= coordinateSpaceCoordinateScale.Y;
|
||||
attributeAccessor.AccessorContent.AsVec4s[i].Z *= coordinateSpaceCoordinateScale.Z;
|
||||
attributeAccessor.AccessorContent.AsVec4s[i].W *= coordinateSpaceCoordinateScale.W;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts and copies based on the specified coordinate scale
|
||||
/// </summary>
|
||||
/// <param name="array">The array to convert and copy</param>
|
||||
/// <param name="coordinateSpaceCoordinateScale">The specified coordinate space</param>
|
||||
/// <returns>The copied and converted coordinate space</returns>
|
||||
public static Vector4[] ConvertVector4CoordinateSpaceAndCopy(Vector4[] array, GLTF.Math.Vector4 coordinateSpaceCoordinateScale)
|
||||
{
|
||||
var returnArray = new Vector4[array.Length];
|
||||
var coordinateScale = coordinateSpaceCoordinateScale.ToUnityVector4Raw();
|
||||
|
||||
for (var i = 0; i < array.Length; i++)
|
||||
{
|
||||
returnArray[i] = array[i];
|
||||
returnArray[i].Scale(coordinateScale);
|
||||
}
|
||||
|
||||
return returnArray;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rewinds the indicies into Unity coordinate space from glTF space
|
||||
/// </summary>
|
||||
/// <param name="attributeAccessor">The attribute accessor to modify</param>
|
||||
public static void FlipTriangleFaces(int[] indices)
|
||||
{
|
||||
for (int i = 0; i < indices.Length; i += 3)
|
||||
{
|
||||
int temp = indices[i];
|
||||
indices[i] = indices[i + 2];
|
||||
indices[i + 2] = temp;
|
||||
}
|
||||
}
|
||||
|
||||
public static Matrix4x4 ToUnityMatrix4x4(this GLTF.Math.Matrix4x4 matrix)
|
||||
{
|
||||
return new Matrix4x4()
|
||||
{
|
||||
m00 = matrix.M11,
|
||||
m01 = matrix.M12,
|
||||
m02 = matrix.M13,
|
||||
m03 = matrix.M14,
|
||||
m10 = matrix.M21,
|
||||
m11 = matrix.M22,
|
||||
m12 = matrix.M23,
|
||||
m13 = matrix.M24,
|
||||
m20 = matrix.M31,
|
||||
m21 = matrix.M32,
|
||||
m22 = matrix.M33,
|
||||
m23 = matrix.M34,
|
||||
m30 = matrix.M41,
|
||||
m31 = matrix.M42,
|
||||
m32 = matrix.M43,
|
||||
m33 = matrix.M44
|
||||
};
|
||||
}
|
||||
|
||||
public static Matrix4x4[] ToUnityMatrix4x4(this GLTF.Math.Matrix4x4[] inMatrixArr)
|
||||
{
|
||||
Matrix4x4[] outMatrixArr = new Matrix4x4[inMatrixArr.Length];
|
||||
for (int i = 0; i < inMatrixArr.Length; ++i)
|
||||
{
|
||||
outMatrixArr[i] = inMatrixArr[i].ToUnityMatrix4x4();
|
||||
}
|
||||
return outMatrixArr;
|
||||
}
|
||||
|
||||
public static Quaternion SwitchHandedness(this Quaternion input)
|
||||
{
|
||||
return new Quaternion(-input.x, input.y, input.z, -input.w);
|
||||
}
|
||||
|
||||
/*
|
||||
public static Vector4 SwitchHandedness(this Vector4 input)
|
||||
{
|
||||
return new Vector4(-input.x, input.y, input.z, -input.w);
|
||||
}
|
||||
|
||||
public static Matrix4x4 SwitchHandedness(this Matrix4x4 matrix)
|
||||
{
|
||||
Vector3 position = matrix.GetColumn(3).SwitchHandedness();
|
||||
Quaternion rotation = Quaternion.LookRotation(matrix.GetColumn(2), matrix.GetColumn(1)).SwitchHandedness();
|
||||
Vector3 scale = new Vector3(matrix.GetColumn(0).magnitude, matrix.GetColumn(1).magnitude, matrix.GetColumn(2).magnitude);
|
||||
|
||||
float epsilon = 0.00001f;
|
||||
|
||||
// Some issues can occurs with non uniform scales
|
||||
if (Mathf.Abs(scale.x - scale.y) > epsilon || Mathf.Abs(scale.y - scale.z) > epsilon || Mathf.Abs(scale.x - scale.z) > epsilon)
|
||||
{
|
||||
Debug.LogWarning("A matrix with non uniform scale is being converted from left to right handed system. This code is not working correctly in this case");
|
||||
}
|
||||
|
||||
// Handle negative scale component in matrix decomposition
|
||||
if (Matrix4x4.Determinant(matrix) < 0)
|
||||
{
|
||||
Quaternion rot = Quaternion.LookRotation(matrix.GetColumn(2), matrix.GetColumn(1));
|
||||
Matrix4x4 corr = Matrix4x4.TRS(matrix.GetColumn(3), rot, Vector3.one).inverse;
|
||||
Matrix4x4 extractedScale = corr * matrix;
|
||||
scale = new Vector3(extractedScale.m00, extractedScale.m11, extractedScale.m22);
|
||||
}
|
||||
|
||||
// convert transform values from left handed to right handed
|
||||
return Matrix4x4.TRS(position, rotation, scale);
|
||||
}
|
||||
*/
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e3a3c8e7f1cdae14fa835ee3580e292f
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,85 @@
|
||||
using System.Collections.Generic;
|
||||
using GLTF.Schema;
|
||||
using UnityEngine;
|
||||
using UnityGLTF.Extensions;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public static class TextMeshExport
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
[UnityEditor.InitializeOnLoadMethod]
|
||||
#else
|
||||
[RuntimeInitializeOnLoadMethod]
|
||||
#endif
|
||||
static void Init()
|
||||
{
|
||||
GLTFSceneExporter.BeforeMaterialExport += BeforeMaterialExport;
|
||||
GLTFSceneExporter.AfterSceneExport += CleanUpRenderTextureCache;
|
||||
}
|
||||
|
||||
private static void CleanUpRenderTextureCache(GLTFSceneExporter _, GLTFRoot __)
|
||||
{
|
||||
if (rtCache == null) return;
|
||||
foreach (var kvp in rtCache)
|
||||
kvp.Value.Release();
|
||||
rtCache.Clear();
|
||||
}
|
||||
|
||||
private static Material tempMat;
|
||||
private static Dictionary<Texture, RenderTexture> rtCache;
|
||||
|
||||
private static bool BeforeMaterialExport(GLTFSceneExporter exporter, GLTFRoot gltfRoot, Material material, GLTFMaterial materialNode)
|
||||
{
|
||||
if (material.shader.name.Contains("TextMeshPro")) // seems to only work for TextMeshPro/Mobile/ right now (SDFAA_HINTED?)
|
||||
{
|
||||
var s = material.shader;
|
||||
// TODO figure out how to properly use the non-mobile shaders
|
||||
var newS = Shader.Find("TestMeshPro/Mobile/Distance Field");
|
||||
#if UNITY_EDITOR
|
||||
if (!newS)
|
||||
{
|
||||
newS = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(UnityEditor.AssetDatabase.GUIDToAssetPath("fe393ace9b354375a9cb14cdbbc28be4")); // same as above
|
||||
}
|
||||
#endif
|
||||
material.shader = newS;
|
||||
|
||||
if (!tempMat) tempMat = new Material(Shader.Find("Unlit/Transparent Cutout"));
|
||||
|
||||
var existingTex = material.mainTexture;
|
||||
if (rtCache == null) rtCache = new Dictionary<Texture, RenderTexture>();
|
||||
if (!rtCache.ContainsKey(existingTex))
|
||||
{
|
||||
var rt = new RenderTexture(existingTex.width, existingTex.height, 0, RenderTextureFormat.ARGB32);
|
||||
if (material.HasProperty("_OutlineSoftness"))
|
||||
material.SetFloat("_OutlineSoftness", 0);
|
||||
// TODO figure out how to get this more smooth
|
||||
Graphics.Blit(existingTex, rt, material);
|
||||
rtCache[existingTex] = rt;
|
||||
rt.anisoLevel = 9;
|
||||
rt.filterMode = FilterMode.Bilinear;
|
||||
}
|
||||
|
||||
tempMat.mainTexture = rtCache[existingTex];
|
||||
|
||||
|
||||
exporter.ExportUnlit(materialNode, tempMat);
|
||||
|
||||
// export material
|
||||
// alternative: double sided, alpha clipping, white RGB + TMPro mainTex R channel as alpha
|
||||
materialNode.DoubleSided = false;
|
||||
materialNode.PbrMetallicRoughness.BaseColorFactor = Color.white.ToNumericsColorLinear();
|
||||
materialNode.AlphaMode = AlphaMode.BLEND;
|
||||
|
||||
material.shader = s;
|
||||
#if UNITY_EDITOR && UNITY_2019_3_OR_NEWER
|
||||
UnityEditor.EditorUtility.ClearDirty(material);
|
||||
#endif
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5dd4c08c7d6d71f4ca7d83fb653d4f9b
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5ecddf923e46d4e4a8a472349578948c
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,18 @@
|
||||
using UnityEngine;
|
||||
using UnityGLTF.Loader;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public abstract class ImporterFactory : ScriptableObject
|
||||
{
|
||||
public abstract GLTFSceneImporter CreateSceneImporter(string gltfFileName, ImportOptions options);
|
||||
}
|
||||
|
||||
public class DefaultImporterFactory : ImporterFactory
|
||||
{
|
||||
public override GLTFSceneImporter CreateSceneImporter(string gltfFileName, ImportOptions options)
|
||||
{
|
||||
return new GLTFSceneImporter(gltfFileName, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 26465c5482163224486cdb865e3a0838
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,150 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Events;
|
||||
using UnityGLTF.Loader;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
/// <summary>
|
||||
/// Component to load a GLTF scene with
|
||||
/// </summary>
|
||||
public class GLTFComponent : MonoBehaviour
|
||||
{
|
||||
public string GLTFUri = null;
|
||||
public bool Multithreaded = true;
|
||||
public bool UseStream = false;
|
||||
public bool AppendStreamingAssets = true;
|
||||
public bool PlayAnimationOnLoad = true;
|
||||
public ImporterFactory Factory = null;
|
||||
public UnityAction onLoadComplete;
|
||||
|
||||
#if UNITY_ANIMATION
|
||||
public IEnumerable<Animation> Animations { get; private set; }
|
||||
#endif
|
||||
|
||||
[SerializeField]
|
||||
private bool loadOnStart = true;
|
||||
|
||||
[SerializeField] private int RetryCount = 10;
|
||||
[SerializeField] private float RetryTimeout = 2.0f;
|
||||
private int numRetries = 0;
|
||||
|
||||
|
||||
public int MaximumLod = 300;
|
||||
public int Timeout = 8;
|
||||
public GLTFSceneImporter.ColliderType Collider = GLTFSceneImporter.ColliderType.None;
|
||||
public GameObject LastLoadedScene { get; private set; } = null;
|
||||
|
||||
[SerializeField]
|
||||
private Shader shaderOverride = null;
|
||||
|
||||
private async void Start()
|
||||
{
|
||||
if (!loadOnStart) return;
|
||||
|
||||
try
|
||||
{
|
||||
await Load();
|
||||
}
|
||||
#if WINDOWS_UWP
|
||||
catch (Exception)
|
||||
#else
|
||||
catch (HttpRequestException)
|
||||
#endif
|
||||
{
|
||||
if (numRetries++ >= RetryCount)
|
||||
throw;
|
||||
|
||||
Debug.LogWarning("Load failed, retrying");
|
||||
await Task.Delay((int)(RetryTimeout * 1000));
|
||||
Start();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task Load()
|
||||
{
|
||||
var importOptions = new ImportOptions
|
||||
{
|
||||
AsyncCoroutineHelper = gameObject.GetComponent<AsyncCoroutineHelper>() ?? gameObject.AddComponent<AsyncCoroutineHelper>()
|
||||
};
|
||||
|
||||
GLTFSceneImporter sceneImporter = null;
|
||||
try
|
||||
{
|
||||
Factory = Factory ?? ScriptableObject.CreateInstance<DefaultImporterFactory>();
|
||||
|
||||
// UseStream is currently not supported...
|
||||
string fullPath;
|
||||
if (AppendStreamingAssets)
|
||||
fullPath = Path.Combine(Application.streamingAssetsPath, GLTFUri.TrimStart(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }));
|
||||
else
|
||||
fullPath = GLTFUri;
|
||||
|
||||
string dir = URIHelper.GetDirectoryName(fullPath);
|
||||
importOptions.DataLoader = new UnityWebRequestLoader(dir);
|
||||
sceneImporter = Factory.CreateSceneImporter(
|
||||
Path.GetFileName(fullPath),
|
||||
importOptions
|
||||
);
|
||||
|
||||
sceneImporter.SceneParent = gameObject.transform;
|
||||
sceneImporter.Collider = Collider;
|
||||
sceneImporter.MaximumLod = MaximumLod;
|
||||
sceneImporter.Timeout = Timeout;
|
||||
sceneImporter.IsMultithreaded = Multithreaded;
|
||||
sceneImporter.CustomShaderName = shaderOverride ? shaderOverride.name : null;
|
||||
|
||||
// for logging progress
|
||||
await sceneImporter.LoadSceneAsync(
|
||||
onLoadComplete:LoadCompleteAction
|
||||
// ,progress: new Progress<ImportProgress>(
|
||||
// p =>
|
||||
// {
|
||||
// Debug.Log("Progress: " + p);
|
||||
// })
|
||||
);
|
||||
|
||||
// Override the shaders on all materials if a shader is provided
|
||||
if (shaderOverride != null)
|
||||
{
|
||||
Renderer[] renderers = gameObject.GetComponentsInChildren<Renderer>();
|
||||
foreach (Renderer renderer in renderers)
|
||||
{
|
||||
renderer.sharedMaterial.shader = shaderOverride;
|
||||
}
|
||||
}
|
||||
|
||||
LastLoadedScene = sceneImporter.LastLoadedScene;
|
||||
|
||||
#if UNITY_ANIMATION
|
||||
Animations = sceneImporter.LastLoadedScene.GetComponents<Animation>();
|
||||
|
||||
if (PlayAnimationOnLoad && Animations.Any())
|
||||
{
|
||||
Animations.First().Play();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
finally
|
||||
{
|
||||
if(importOptions.DataLoader != null)
|
||||
{
|
||||
sceneImporter?.Dispose();
|
||||
sceneImporter = null;
|
||||
importOptions.DataLoader = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void LoadCompleteAction(GameObject obj, ExceptionDispatchInfo exceptionDispatchInfo)
|
||||
{
|
||||
onLoadComplete?.Invoke();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9087a95f22bcee64ebc45f6deec08714
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 200
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,141 @@
|
||||
#if ENABLE_INPUT_SYSTEM && HAVE_INPUTSYSTEM
|
||||
#define NEW_INPUT
|
||||
#endif
|
||||
|
||||
using System.Collections;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Events;
|
||||
#if NEW_INPUT
|
||||
using UnityEngine.InputSystem;
|
||||
#endif
|
||||
using UnityGLTF.Timeline;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public class GLTFRecorderComponent : MonoBehaviour
|
||||
{
|
||||
public string outputFile = "Assets/Recordings/Recorded_<Timestamp>.glb";
|
||||
public Transform exportRoot;
|
||||
public bool recordBlendShapes = true;
|
||||
public bool recordRootInWorldSpace = true;
|
||||
public bool recordAnimationPointer = false;
|
||||
|
||||
#if NEW_INPUT
|
||||
public InputAction recordingKey = new InputAction(binding: "<Keyboard>/F11");
|
||||
#else
|
||||
public KeyCode recordingKey = KeyCode.F11;
|
||||
#endif
|
||||
|
||||
public bool IsRecording => recorder?.IsRecording ?? false;
|
||||
protected GLTFRecorder recorder;
|
||||
|
||||
public UnityEvent recordingStarted;
|
||||
public UnityEvent<string> recordingEnded;
|
||||
|
||||
private double CurrentTime =>
|
||||
#if UNITY_2020_1_OR_NEWER
|
||||
Time.timeAsDouble;
|
||||
#else
|
||||
Time.time;
|
||||
#endif
|
||||
|
||||
[ContextMenu("Start Recording")]
|
||||
public virtual void StartRecording()
|
||||
{
|
||||
if (!isActiveAndEnabled) return;
|
||||
|
||||
var settings = GLTFSettings.GetOrCreateSettings();
|
||||
var shouldRecordBlendShapes = recordBlendShapes;
|
||||
if (settings.BlendShapeExportProperties == GLTFSettings.BlendShapeExportPropertyFlags.None && recordBlendShapes)
|
||||
{
|
||||
Debug.LogWarning("Attempting to record blend shapes but export is disabled in ProjectSettings/UnityGLTF. Set BlendShapeExportProperties to something other than \"None\" if you want to export them.");
|
||||
shouldRecordBlendShapes = false;
|
||||
}
|
||||
|
||||
var shouldUseAnimationPointer = recordAnimationPointer;
|
||||
if (!settings.UseAnimationPointer && recordAnimationPointer)
|
||||
{
|
||||
Debug.LogWarning("Attempting to record KHR_animation_pointer but that is disabled in ProjectSettings/UnityGLTF. Please enable it.");
|
||||
shouldUseAnimationPointer = false;
|
||||
}
|
||||
|
||||
recorder = new GLTFRecorder(exportRoot, shouldRecordBlendShapes, recordRootInWorldSpace, shouldUseAnimationPointer);
|
||||
recorder.StartRecording(CurrentTime);
|
||||
recordingStarted?.Invoke();
|
||||
|
||||
StartCoroutine(_UpdateRecording());
|
||||
}
|
||||
|
||||
[ContextMenu("Stop Recording")]
|
||||
public virtual void StopRecording()
|
||||
{
|
||||
var filename = outputFile.Replace("<Timestamp>", System.DateTime.Now.ToString("yyyyMMdd-HHmmss"));
|
||||
recorder.EndRecording(filename);
|
||||
recordingEnded?.Invoke(filename);
|
||||
}
|
||||
|
||||
private void ToggleRecording()
|
||||
{
|
||||
if (!exportRoot || string.IsNullOrEmpty(outputFile))
|
||||
{
|
||||
Debug.LogError($"[GLTFRecorderComponent] Can't record, please assign exportRoot and outputFile on {nameof(GLTFRecorderComponent)}", this);
|
||||
return;
|
||||
}
|
||||
|
||||
if(IsRecording)
|
||||
{
|
||||
StopRecording();
|
||||
Debug.Log("Recording Stopped", this);
|
||||
}
|
||||
else {
|
||||
StartRecording();
|
||||
Debug.Log("Recording Started", this);
|
||||
}
|
||||
}
|
||||
|
||||
#if NEW_INPUT
|
||||
private void Start()
|
||||
{
|
||||
recordingKey.performed += _ => ToggleRecording();
|
||||
}
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
recordingKey.Enable();
|
||||
}
|
||||
#else
|
||||
protected virtual void Update()
|
||||
{
|
||||
if(Input.GetKeyDown(recordingKey))
|
||||
ToggleRecording();
|
||||
}
|
||||
#endif
|
||||
|
||||
protected virtual void OnDisable()
|
||||
{
|
||||
if(IsRecording)
|
||||
StopRecording();
|
||||
#if NEW_INPUT
|
||||
recordingKey.Disable();
|
||||
#endif
|
||||
}
|
||||
|
||||
protected virtual void UpdateRecording()
|
||||
{
|
||||
if(CurrentTime > recorder.LastRecordedTime)
|
||||
recorder.UpdateRecording(CurrentTime);
|
||||
}
|
||||
|
||||
private IEnumerator _UpdateRecording()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
yield return new WaitForEndOfFrame();
|
||||
if (!IsRecording)
|
||||
yield break;
|
||||
|
||||
UpdateRecording();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e76d60ddbac22cd4ba183f725ba62c5c
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 99a6a54edfc45604ab2a687a161f520b
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e2215b68d185249408d7b16c1c8799b0
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,227 @@
|
||||
#if UNITY_EDITOR && UNITY_IMGUI
|
||||
#define SHOW_SETTINGS_EDITOR
|
||||
#endif
|
||||
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using System.IO;
|
||||
using UnityEngine.UIElements;
|
||||
using UnityGLTF.Cache;
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
#if SHOW_SETTINGS_EDITOR
|
||||
internal class GltfSettingsProvider : SettingsProvider
|
||||
{
|
||||
private GLTFSettings settings;
|
||||
private SerializedObject m_SerializedObject;
|
||||
private SerializedProperty showDefaultReferenceNameWarning, showNamingRecommendationHint;
|
||||
|
||||
public override void OnGUI(string searchContext)
|
||||
{
|
||||
EditorGUIUtility.labelWidth = 200;
|
||||
if (m_SerializedObject == null)
|
||||
{
|
||||
if (!settings) settings = GLTFSettings.GetOrCreateSettings();
|
||||
m_SerializedObject = new SerializedObject(settings);
|
||||
}
|
||||
|
||||
SerializedProperty prop = m_SerializedObject.GetIterator();
|
||||
prop.NextVisible(true);
|
||||
if (prop.NextVisible(true))
|
||||
{
|
||||
do
|
||||
{
|
||||
EditorGUILayout.PropertyField(prop, true);
|
||||
switch (prop.name)
|
||||
{
|
||||
case nameof(GLTFSettings.UseCaching):
|
||||
EditorGUILayout.BeginHorizontal();
|
||||
if (GUILayout.Button($"Clear Cache ({(exportCacheByteLength / (1024f * 1024f)):F2} MB)")) {
|
||||
ExportCache.Clear();
|
||||
CalculateCacheStats();
|
||||
}
|
||||
if (GUILayout.Button("Open Cache Directory ↗"))
|
||||
ExportCache.OpenCacheDirectory();
|
||||
EditorGUILayout.EndHorizontal();
|
||||
break;
|
||||
}
|
||||
}
|
||||
while (prop.NextVisible(false));
|
||||
}
|
||||
|
||||
if(m_SerializedObject.hasModifiedProperties) {
|
||||
m_SerializedObject.ApplyModifiedProperties();
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnActivate(string searchContext, VisualElement rootElement)
|
||||
{
|
||||
base.OnActivate(searchContext, rootElement);
|
||||
CalculateCacheStats();
|
||||
}
|
||||
|
||||
private long exportCacheByteLength = 0;
|
||||
private void CalculateCacheStats()
|
||||
{
|
||||
var files = new List<FileInfo>();
|
||||
exportCacheByteLength = ExportCache.CalculateCacheSize(files);
|
||||
}
|
||||
|
||||
[SettingsProvider]
|
||||
public static SettingsProvider CreateGltfSettingsProvider()
|
||||
{
|
||||
GLTFSettings.GetOrCreateSettings();
|
||||
return new GltfSettingsProvider("Project/UnityGLTF", SettingsScope.Project);
|
||||
}
|
||||
|
||||
public GltfSettingsProvider(string path, SettingsScope scopes, IEnumerable<string> keywords = null) : base(path, scopes, keywords) { }
|
||||
}
|
||||
#endif
|
||||
|
||||
public class GLTFSettings : ScriptableObject
|
||||
{
|
||||
private const string k_PreferencesPrefix = "UnityGLTF_Preferences_";
|
||||
private const string k_SettingsFileName = "UnityGLTFSettings.asset";
|
||||
public const string k_RuntimeAndEditorSettingsPath = "Assets/Resources/" + k_SettingsFileName;
|
||||
|
||||
[System.Flags]
|
||||
public enum BlendShapeExportPropertyFlags
|
||||
{
|
||||
None = 0,
|
||||
PositionOnly = 1,
|
||||
Normal = 2,
|
||||
Tangent = 4,
|
||||
All = ~0
|
||||
}
|
||||
|
||||
[Header("Export Settings")]
|
||||
[SerializeField]
|
||||
private bool exportNames = true;
|
||||
[SerializeField]
|
||||
[Tooltip("If on, the entire texture path will be preserved. If off (default), textures are exported at root level.")]
|
||||
private bool exportFullPath = false;
|
||||
[SerializeField]
|
||||
private bool requireExtensions = false;
|
||||
|
||||
[Header("Export Visibility")]
|
||||
[SerializeField]
|
||||
[Tooltip("Uses Camera.main layer settings to filter which objects are exported")]
|
||||
private bool useMainCameraVisibility = true;
|
||||
[SerializeField]
|
||||
[Tooltip("glTF does not support visibility state. If this setting is true, disabled GameObjects will still be exported and be visible in the glTF file.")]
|
||||
private bool exportDisabledGameObjects = false;
|
||||
|
||||
[Header("Export Textures")]
|
||||
[SerializeField]
|
||||
[Tooltip("(Experimental) Exports PNG/JPEG directly from disk instead of re-encoding from Unity's import result. No channel repacking will happen for these textures. Textures in other formats (PSD, TGA etc) not supported by glTF and in-memory textures (e.g. RenderTextures) are always re-encoded.")]
|
||||
private bool tryExportTexturesFromDisk = false;
|
||||
[SerializeField] [Tooltip("Determines texture export type (PNG or JPEG) based on alpha channel. When false, always exports lossless PNG files.")]
|
||||
private bool useTextureFileTypeHeuristic = true;
|
||||
[SerializeField] [Tooltip("Quality setting for exported JPEG files.")]
|
||||
private int defaultJpegQuality = 90;
|
||||
|
||||
[Header("Export Animation")]
|
||||
[SerializeField]
|
||||
private bool exportAnimations = true;
|
||||
[Tooltip("(Experimental) Export animations using KHR_animation_pointer. Requires the viewer to also support this extension.")]
|
||||
[SerializeField]
|
||||
private bool useAnimationPointer = false;
|
||||
[SerializeField]
|
||||
[Tooltip("Some viewers can't distinguish between animation clips that have the same name. This option ensures all exported animation names are unique.")]
|
||||
private bool uniqueAnimationNames = false;
|
||||
[SerializeField]
|
||||
private bool bakeSkinnedMeshes = false;
|
||||
|
||||
[Header("Export Mesh Data")]
|
||||
[SerializeField]
|
||||
private BlendShapeExportPropertyFlags blendShapeExportProperties = BlendShapeExportPropertyFlags.All;
|
||||
[SerializeField]
|
||||
[Tooltip("(Experimental) Use Sparse Accessors for blend shape export. Not supported on some viewers.")]
|
||||
private bool blendShapeExportSparseAccessors = true;
|
||||
[SerializeField]
|
||||
[Tooltip("If off, vertex colors are not exported. Vertex Colors aren't supported in some viewers (e.g. Google's SceneViewer).")]
|
||||
private bool exportVertexColors = true;
|
||||
|
||||
[Header("Export Cache")]
|
||||
[Tooltip("When enabled textures will be cached to disc for faster export times.\n(The cache size is reduced to stay below 1024 MB when the Editor quits)")]
|
||||
public bool UseCaching = true;
|
||||
|
||||
public bool ExportNames { get => exportNames; set => exportNames = value; }
|
||||
public bool ExportFullPath { get => exportFullPath; set => exportFullPath = value; }
|
||||
public bool UseMainCameraVisibility { get => useMainCameraVisibility; set => useMainCameraVisibility = value; }
|
||||
public bool RequireExtensions { get => requireExtensions; set => requireExtensions = value; }
|
||||
public bool TryExportTexturesFromDisk { get => tryExportTexturesFromDisk; set => tryExportTexturesFromDisk = value; }
|
||||
public bool UseTextureFileTypeHeuristic { get => useTextureFileTypeHeuristic; set => useTextureFileTypeHeuristic = value; }
|
||||
public bool ExportVertexColors { get => exportVertexColors; set => exportVertexColors = value; }
|
||||
public int DefaultJpegQuality { get => defaultJpegQuality; set => defaultJpegQuality = value; }
|
||||
public bool ExportDisabledGameObjects { get => exportDisabledGameObjects; set => exportDisabledGameObjects = value; }
|
||||
public bool ExportAnimations { get => exportAnimations; set => exportAnimations = value; }
|
||||
public bool UseAnimationPointer { get => useAnimationPointer; set => useAnimationPointer = value; }
|
||||
public bool UniqueAnimationNames { get => uniqueAnimationNames; set => uniqueAnimationNames = value; }
|
||||
public bool BlendShapeExportSparseAccessors { get => blendShapeExportSparseAccessors; set => blendShapeExportSparseAccessors = value; }
|
||||
public BlendShapeExportPropertyFlags BlendShapeExportProperties { get => blendShapeExportProperties; set => blendShapeExportProperties = value; }
|
||||
public bool BakeSkinnedMeshes { get => bakeSkinnedMeshes; set => bakeSkinnedMeshes = value; }
|
||||
|
||||
|
||||
#if UNITY_EDITOR
|
||||
private const string SaveFolderPathPref = k_PreferencesPrefix + "SaveFolderPath";
|
||||
public string SaveFolderPath
|
||||
{
|
||||
get => EditorPrefs.GetString(SaveFolderPathPref, null);
|
||||
set => EditorPrefs.SetString(SaveFolderPathPref, value);
|
||||
}
|
||||
#endif
|
||||
|
||||
internal static GLTFSettings cachedSettings;
|
||||
|
||||
public static GLTFSettings GetOrCreateSettings()
|
||||
{
|
||||
if (!TryGetSettings(out var settings))
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
settings = ScriptableObject.CreateInstance<GLTFSettings>();
|
||||
var dir = Path.GetDirectoryName(k_RuntimeAndEditorSettingsPath);
|
||||
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
|
||||
AssetDatabase.CreateAsset(settings, k_RuntimeAndEditorSettingsPath);
|
||||
AssetDatabase.SaveAssets();
|
||||
#else
|
||||
settings = ScriptableObject.CreateInstance<GLTFSettings>();
|
||||
#endif
|
||||
}
|
||||
cachedSettings = settings;
|
||||
return settings;
|
||||
}
|
||||
|
||||
public static bool TryGetSettings(out GLTFSettings settings)
|
||||
{
|
||||
settings = cachedSettings;
|
||||
if (settings)
|
||||
return true;
|
||||
|
||||
settings = Resources.Load<GLTFSettings>(Path.GetFileNameWithoutExtension(k_SettingsFileName));
|
||||
|
||||
#if UNITY_EDITOR
|
||||
if (!settings)
|
||||
{
|
||||
settings = AssetDatabase.LoadAssetAtPath<GLTFSettings>(k_RuntimeAndEditorSettingsPath);
|
||||
}
|
||||
if (!settings)
|
||||
{
|
||||
var allSettings = AssetDatabase.FindAssets("t:GLTFSettings");
|
||||
if (allSettings.Length > 0)
|
||||
{
|
||||
settings = AssetDatabase.LoadAssetAtPath<GLTFSettings>(AssetDatabase.GUIDToAssetPath(allSettings[0]));
|
||||
}
|
||||
}
|
||||
cachedSettings = settings;
|
||||
return settings;
|
||||
#else
|
||||
return settings;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9d9a5969691dba845877d0a52b6d9397
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,65 @@
|
||||
using UnityEngine;
|
||||
using UnityGLTF.Cache;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
/// <summary>
|
||||
/// Instantiated GLTF Object component that gets added to the root of every GLTF game object created by a scene importer.
|
||||
/// </summary>
|
||||
public class InstantiatedGLTFObject : MonoBehaviour
|
||||
{
|
||||
/// <summary>
|
||||
/// Ref-counted cache data for this object.
|
||||
/// The same instance of this cached data will be used for all copies of this GLTF object,
|
||||
/// and the data gets cleaned up when the ref counts goes to 0.
|
||||
/// </summary>
|
||||
private RefCountedCacheData cachedData;
|
||||
public RefCountedCacheData CachedData
|
||||
{
|
||||
get
|
||||
{
|
||||
return cachedData;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
if (cachedData != value)
|
||||
{
|
||||
if (cachedData != null)
|
||||
{
|
||||
cachedData.DecreaseRefCount();
|
||||
}
|
||||
|
||||
cachedData = value;
|
||||
|
||||
if (cachedData != null)
|
||||
{
|
||||
cachedData.IncreaseRefCount();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Duplicates the instantiated GLTF object.
|
||||
/// Note that this should always be called if you intend to create a new instance of a GLTF object,
|
||||
/// in order to properly preserve the ref count of the dynamically loaded mesh data, otherwise
|
||||
/// you will run into a memory leak due to non-destroyed meshes, textures and materials.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public InstantiatedGLTFObject Duplicate()
|
||||
{
|
||||
GameObject duplicatedObject = Instantiate(gameObject);
|
||||
|
||||
InstantiatedGLTFObject newGltfObjectComponent = duplicatedObject.GetComponent<InstantiatedGLTFObject>();
|
||||
newGltfObjectComponent.CachedData = CachedData;
|
||||
|
||||
return newGltfObjectComponent;
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
CachedData = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 943fbcf4d915b934db023669fa205a37
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8b6a60ae7ada43ce81c9fe3d7d34cdb3
|
||||
timeCreated: 1651350262
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace UnityGLTF.JsonPointer
|
||||
{
|
||||
public interface IJsonPointerResolver
|
||||
{
|
||||
bool TryResolve(object target, ref string path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8c60ec8461d64f80a335777129bdde18
|
||||
timeCreated: 1651350280
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9b9e509156e15f242836bedd245ddd21
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,73 @@
|
||||
using System.IO;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace UnityGLTF.Loader
|
||||
{
|
||||
public class FileLoader : IDataLoader2
|
||||
{
|
||||
private readonly string _rootDirectoryPath;
|
||||
|
||||
public FileLoader(string rootDirectoryPath)
|
||||
{
|
||||
_rootDirectoryPath = rootDirectoryPath;
|
||||
}
|
||||
|
||||
public Task<Stream> LoadStreamAsync(string relativeFilePath)
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
string path = Path.Combine(_rootDirectoryPath, relativeFilePath).Replace("\\", "/");
|
||||
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
path = Path.Combine(_rootDirectoryPath, Uri.UnescapeDataString(relativeFilePath)).Replace("\\", "/");
|
||||
}
|
||||
|
||||
if (UnityEditor.AssetDatabase.GetMainAssetTypeAtPath(path) == typeof(UnityEngine.Texture2D))
|
||||
{
|
||||
var stream = new GLTFSceneImporter.AssetDatabaseStream(path);
|
||||
return Task.FromResult((Stream) stream);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !WINDOWS_UWP && !UNITY_WEBGL
|
||||
// seems the Editor locks up in some cases when directly using Task.Run(() => {})
|
||||
if (UnityEngine.Application.isPlaying)
|
||||
{
|
||||
return Task.Run(() => LoadStream(relativeFilePath));
|
||||
}
|
||||
#endif
|
||||
return Task.FromResult(LoadStream(relativeFilePath));
|
||||
}
|
||||
|
||||
public Stream LoadStream(string relativeFilePath)
|
||||
{
|
||||
if (relativeFilePath == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(relativeFilePath));
|
||||
}
|
||||
|
||||
if (File.Exists(relativeFilePath))
|
||||
return File.OpenRead(relativeFilePath);
|
||||
|
||||
string pathToLoad = Path.Combine(_rootDirectoryPath, relativeFilePath);
|
||||
if (!File.Exists(pathToLoad))
|
||||
{
|
||||
pathToLoad = Path.Combine(_rootDirectoryPath, Uri.UnescapeDataString(relativeFilePath));
|
||||
}
|
||||
|
||||
if (!File.Exists(pathToLoad))
|
||||
{
|
||||
if (relativeFilePath.ToLowerInvariant().EndsWith(".bin"))
|
||||
throw new FileNotFoundException("Buffer file " + relativeFilePath + " not found in " + _rootDirectoryPath + ", complete path: " + pathToLoad, relativeFilePath);
|
||||
|
||||
UnityEngine.Debug.LogError("Buffer file " + relativeFilePath + " not found in " + _rootDirectoryPath + ", complete path: " + pathToLoad);
|
||||
return InvalidStream;
|
||||
}
|
||||
|
||||
return File.OpenRead(pathToLoad);
|
||||
}
|
||||
|
||||
internal static readonly Stream InvalidStream = new MemoryStream();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e1980a22c6cc4ce4e920022d7d9e941d
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace UnityGLTF.Loader
|
||||
{
|
||||
public interface IDataLoader
|
||||
{
|
||||
Task<Stream> LoadStreamAsync(string relativeFilePath);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fdb6a96a5ee34824685713dbad74cf51
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,9 @@
|
||||
using System.IO;
|
||||
|
||||
namespace UnityGLTF.Loader
|
||||
{
|
||||
public interface IDataLoader2 : IDataLoader
|
||||
{
|
||||
Stream LoadStream(string relativeFilePath);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 88e0d77167dc3af489e57a17abcde939
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace UnityGLTF.Loader
|
||||
{
|
||||
[Obsolete("Please switch to IDataLoader. This interface is deprecated and will be removed in a future release.")]
|
||||
public interface ILoader
|
||||
{
|
||||
Task LoadStream(string relativeFilePath);
|
||||
|
||||
void LoadStreamSync(string jsonFilePath);
|
||||
|
||||
Stream LoadedStream { get; }
|
||||
|
||||
bool HasSyncLoadMethod { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ba15ab25bba758f4e8867413d5011747
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,56 @@
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace UnityGLTF.Loader
|
||||
{
|
||||
#pragma warning disable CS0618 // Type or member is obsolete
|
||||
/// <summary>
|
||||
/// Wrapper utility for exposing an <see cref="ILoader"/> as a <see cref="IDataLoader"/> (and if appropriate, <see cref="IDataLoader2"/>).
|
||||
/// </summary>
|
||||
public static class LegacyLoaderWrapper
|
||||
{
|
||||
public static IDataLoader Wrap(ILoader loader)
|
||||
{
|
||||
if (loader == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (loader.HasSyncLoadMethod)
|
||||
{
|
||||
return new LegacyLoader2(loader);
|
||||
}
|
||||
return new LegacyLoader(loader);
|
||||
}
|
||||
|
||||
private class LegacyLoader : IDataLoader
|
||||
{
|
||||
protected readonly ILoader _loader;
|
||||
|
||||
public LegacyLoader(ILoader loader)
|
||||
{
|
||||
_loader = loader;
|
||||
}
|
||||
|
||||
public Task<Stream> LoadStreamAsync(string relativeFilePath)
|
||||
{
|
||||
_loader.LoadStream(relativeFilePath);
|
||||
return Task.FromResult(_loader.LoadedStream);
|
||||
}
|
||||
}
|
||||
|
||||
private class LegacyLoader2 : LegacyLoader, IDataLoader2
|
||||
{
|
||||
public LegacyLoader2(ILoader loader) :
|
||||
base(loader)
|
||||
{
|
||||
}
|
||||
|
||||
public Stream LoadStream(string relativeFilePath)
|
||||
{
|
||||
_loader.LoadStreamSync(relativeFilePath);
|
||||
return _loader.LoadedStream;
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma warning restore CS0618 // Type or member is obsolete
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0ca569386b974e44d8f914fdd0781b2a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,39 @@
|
||||
#if WINDOWS_UWP
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Windows.Storage;
|
||||
using System;
|
||||
using System.Collections;
|
||||
|
||||
namespace UnityGLTF.Loader
|
||||
{
|
||||
public class StorageFolderLoader : IDataLoader
|
||||
{
|
||||
private StorageFolder _rootFolder;
|
||||
|
||||
public StorageFolderLoader(StorageFolder rootFolder)
|
||||
{
|
||||
_rootFolder = rootFolder;
|
||||
}
|
||||
|
||||
public async Task<Stream> LoadStreamAsync(string relativeFilePath)
|
||||
{
|
||||
if (relativeFilePath == null)
|
||||
{
|
||||
throw new ArgumentNullException("relativeFilePath");
|
||||
}
|
||||
|
||||
StorageFolder parentFolder = _rootFolder;
|
||||
string fileName = Path.GetFileName(relativeFilePath);
|
||||
if (relativeFilePath != fileName)
|
||||
{
|
||||
string folderToLoad = relativeFilePath.Substring(0, relativeFilePath.Length - fileName.Length);
|
||||
parentFolder = await _rootFolder.GetFolderAsync(folderToLoad);
|
||||
}
|
||||
|
||||
StorageFile bufferFile = await parentFolder.GetFileAsync(fileName);
|
||||
return await bufferFile.OpenStreamForReadAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8e7fd7d6556ddd446903db465957f23d
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,97 @@
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Networking;
|
||||
|
||||
namespace UnityGLTF.Loader
|
||||
{
|
||||
public class UnityWebRequestLoader : IDataLoader
|
||||
{
|
||||
private string dir;
|
||||
|
||||
public UnityWebRequestLoader(string dir)
|
||||
{
|
||||
this.dir = dir;
|
||||
}
|
||||
#if UNITY_WEBREQUEST
|
||||
public async Task<Stream> LoadStreamAsync(string relativeFilePath)
|
||||
{
|
||||
var path = Path.Combine(dir, relativeFilePath).Replace("\\","/");
|
||||
if (File.Exists(path))
|
||||
path = "file://" + Path.GetFullPath(path);
|
||||
var request = UnityWebRequest.Get(path);
|
||||
// request.downloadHandler = new DownloadStreamHandler(new byte[1024 * 1024]);
|
||||
var asyncOperation = request.SendWebRequest();
|
||||
|
||||
while (!asyncOperation.isDone) {
|
||||
await Task.Yield();
|
||||
}
|
||||
|
||||
#if UNITY_2020_1_OR_NEWER
|
||||
if (request.result != UnityWebRequest.Result.Success)
|
||||
#else
|
||||
if (request.isNetworkError || request.isHttpError)
|
||||
#endif
|
||||
{
|
||||
Debug.LogError($"Error when loading {relativeFilePath} ({path}): {request.error}");
|
||||
return null;
|
||||
}
|
||||
|
||||
var results = request.downloadHandler.data;
|
||||
var stream = new MemoryStream(results, 0, results.Length, false, true);
|
||||
return stream;
|
||||
}
|
||||
#else
|
||||
public async Task<Stream> LoadStreamAsync(string relativeFilePath)
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
throw new System.ApplicationException("The module com.unity.modules.unitywebrequest is required for this functionality. Please install it in your project.");
|
||||
}
|
||||
#endif
|
||||
|
||||
// TODO: figure out how to do this correctly in a streaming fashion.
|
||||
// private class DownloadStreamHandler : DownloadHandlerScript
|
||||
// {
|
||||
// private ulong expectedTotalBytes = 0;
|
||||
// private Stream stream;
|
||||
// public Stream GetStream()
|
||||
// {
|
||||
// return stream;
|
||||
// }
|
||||
//
|
||||
// public DownloadStreamHandler(byte[] buffer) : base(buffer)
|
||||
// {
|
||||
// stream = new MemoryStream(buffer, true);
|
||||
// }
|
||||
//
|
||||
// protected override bool ReceiveData(byte[] data, int dataLength)
|
||||
// {
|
||||
// if(data == null || data.Length < 1)
|
||||
// {
|
||||
// Debug.Log("LoggingDownloadHandler :: ReceiveData - received a null/empty buffer");
|
||||
// return false;
|
||||
// }
|
||||
//
|
||||
// stream.Write(data, 0, dataLength);
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// protected override byte[] GetData()
|
||||
// {
|
||||
// throw new System.NotSupportedException("This is a stream, can't get all bytes");
|
||||
// }
|
||||
//
|
||||
// protected override void CompleteContent()
|
||||
// {
|
||||
// Debug.Log("LoggingDownloadHandler :: CompleteContent - DOWNLOAD COMPLETE!");
|
||||
// }
|
||||
//
|
||||
// protected override void ReceiveContentLengthHeader(ulong contentLength)
|
||||
// {
|
||||
// Debug.Log(string.Format("LoggingDownloadHandler :: ReceiveContentLength - length {0}", contentLength));
|
||||
// expectedTotalBytes = contentLength;
|
||||
// stream.SetLength((long) contentLength);
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f570680f27e849d59aeaa47194bfa5e4
|
||||
timeCreated: 1650878357
|
||||
@@ -0,0 +1,101 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
#if WINDOWS_UWP
|
||||
using Windows.Web.Http;
|
||||
using Windows.Security;
|
||||
using Windows.Storage.Streams;
|
||||
#else
|
||||
using System.Net.Http;
|
||||
using System.Net.Security;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
#endif
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace UnityGLTF.Loader
|
||||
{
|
||||
public class WebRequestLoader : IDataLoader
|
||||
{
|
||||
private readonly HttpClient httpClient = new HttpClient();
|
||||
private readonly Uri baseAddress;
|
||||
|
||||
public WebRequestLoader(string rootUri)
|
||||
{
|
||||
#if !WINDOWS_UWP
|
||||
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
|
||||
#endif
|
||||
baseAddress = new Uri(rootUri);
|
||||
}
|
||||
|
||||
public async Task<Stream> LoadStreamAsync(string gltfFilePath)
|
||||
{
|
||||
if (gltfFilePath == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(gltfFilePath));
|
||||
}
|
||||
|
||||
HttpResponseMessage response;
|
||||
try
|
||||
{
|
||||
#if WINDOWS_UWP
|
||||
response = await httpClient.GetAsync(new Uri(baseAddress, gltfFilePath));
|
||||
#else
|
||||
var tokenSource = new CancellationTokenSource(30000);
|
||||
response = await httpClient.GetAsync(new Uri(baseAddress, gltfFilePath), tokenSource.Token);
|
||||
#endif
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
#if WINDOWS_UWP
|
||||
throw new Exception("Connection timeout");
|
||||
#else
|
||||
throw new HttpRequestException("Connection timeout");
|
||||
#endif
|
||||
}
|
||||
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
// HACK: Download the whole file before returning the stream
|
||||
// Ideally the parsers would wait for data to be available, but they don't.
|
||||
var result = new MemoryStream((int?)response.Content.Headers.ContentLength ?? 5000);
|
||||
#if WINDOWS_UWP
|
||||
await response.Content.WriteToStreamAsync(result.AsOutputStream());
|
||||
#else
|
||||
await response.Content.CopyToAsync(result);
|
||||
#endif
|
||||
response.Dispose();
|
||||
return result;
|
||||
}
|
||||
|
||||
#if !WINDOWS_UWP
|
||||
// enables HTTPS support
|
||||
// https://answers.unity.com/questions/50013/httpwebrequestgetrequeststream-https-certificate-e.html
|
||||
private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
|
||||
{
|
||||
bool isOk = true;
|
||||
// If there are errors in the certificate chain, look at each error to determine the cause.
|
||||
if (errors != SslPolicyErrors.None)
|
||||
{
|
||||
for (int i = 0; i<chain.ChainStatus.Length; i++)
|
||||
{
|
||||
if (chain.ChainStatus[i].Status != X509ChainStatusFlags.RevocationStatusUnknown)
|
||||
{
|
||||
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
|
||||
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
|
||||
chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
|
||||
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
|
||||
bool chainIsValid = chain.Build((X509Certificate2)certificate);
|
||||
if (!chainIsValid)
|
||||
{
|
||||
isOk = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return isOk;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 23ded4d709de5b543811a96389760fc9
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
#if WINDOWS_UWP
|
||||
using Windows.System;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public class MemoryChecker
|
||||
{
|
||||
private bool outOfMemory = false;
|
||||
|
||||
/// <summary>
|
||||
/// Allows polling for app low memory situation. Listens to Application.lowMemory, which works for iOS and Android.
|
||||
/// Also listens to Windows-specific MemoryManager.AppMemoryUsageIncreased.
|
||||
/// </summary>
|
||||
public MemoryChecker()
|
||||
{
|
||||
Application.lowMemory += Application_lowMemory;
|
||||
|
||||
#if WINDOWS_UWP
|
||||
MemoryManager.AppMemoryUsageIncreased += MemoryManager_AppMemoryUsageIncreased;
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// If the OS has notified the app that it is low on memory since MemoryChecker was constructed, this method will throw an OutOfMemoryException.
|
||||
/// Once it throws once, it will continue to throw. Callers are advised to construct a new MemoryChecker after memory usage has gone down.
|
||||
/// </summary>
|
||||
public void ThrowIfOutOfMemory()
|
||||
{
|
||||
if (outOfMemory)
|
||||
{
|
||||
throw new OutOfMemoryException();
|
||||
}
|
||||
}
|
||||
|
||||
private void Application_lowMemory()
|
||||
{
|
||||
outOfMemory = true;
|
||||
}
|
||||
|
||||
#if WINDOWS_UWP
|
||||
private void MemoryManager_AppMemoryUsageIncreased(object sender, object e)
|
||||
{
|
||||
if (MemoryManager.AppMemoryUsageLevel == AppMemoryUsageLevel.OverLimit)
|
||||
{
|
||||
outOfMemory = true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4bde1c330cae17541b9fb48d321d1722
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 463af91555c2fdb479c0951afcf7a7d2
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,62 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
[ExecuteAlways, ImageEffectAllowedInSceneView]
|
||||
public class RoughRefraction : MonoBehaviour
|
||||
{
|
||||
private readonly Dictionary<Camera, RenderTexture> renderTextureCache = new Dictionary<Camera, RenderTexture>();
|
||||
private static readonly int CameraOpaqueTexture = Shader.PropertyToID("_CameraOpaqueTexture");
|
||||
|
||||
private void OnDisable()
|
||||
{
|
||||
if (renderTextureCache != null) {
|
||||
foreach(var kvp in renderTextureCache)
|
||||
RenderTexture.ReleaseTemporary(kvp.Value);
|
||||
}
|
||||
renderTextureCache?.Clear();
|
||||
}
|
||||
|
||||
private void OnPreRender()
|
||||
{
|
||||
SetTexture();
|
||||
}
|
||||
|
||||
private void SetTexture()
|
||||
{
|
||||
var current = Camera.current;
|
||||
if (!renderTextureCache.ContainsKey(current))
|
||||
{
|
||||
Shader.SetGlobalTexture(CameraOpaqueTexture, Texture2D.blackTexture);
|
||||
return;
|
||||
}
|
||||
|
||||
Shader.SetGlobalTexture(CameraOpaqueTexture, renderTextureCache[current]);
|
||||
}
|
||||
|
||||
[ImageEffectOpaque]
|
||||
private void OnRenderImage(RenderTexture src, RenderTexture dest)
|
||||
{
|
||||
var dsc = src.descriptor;
|
||||
dsc.useMipMap = true;
|
||||
dsc.autoGenerateMips = false;
|
||||
dsc.msaaSamples = 1;
|
||||
dsc.width = Mathf.ClosestPowerOfTwo(dsc.width);
|
||||
dsc.height = Mathf.ClosestPowerOfTwo(dsc.height);
|
||||
|
||||
var current = Camera.current;
|
||||
if (!renderTextureCache.ContainsKey(current))
|
||||
renderTextureCache.Add(current, null);
|
||||
if(renderTextureCache[current])
|
||||
RenderTexture.ReleaseTemporary(renderTextureCache[current]);
|
||||
|
||||
renderTextureCache[current] = RenderTexture.GetTemporary(dsc);
|
||||
renderTextureCache[current].filterMode = FilterMode.Trilinear;
|
||||
// temp[current].useMipMap = true;
|
||||
|
||||
Graphics.Blit(src, renderTextureCache[current]);
|
||||
renderTextureCache[current].GenerateMips();
|
||||
Graphics.Blit(src, dest);
|
||||
|
||||
SetTexture();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2b5788589ee445e45bf87cdf1ec6ee90
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,86 @@
|
||||
#if HAVE_URP_12_OR_NEWER || HAVE_URP_10_OR_NEWER
|
||||
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
using UnityEngine.Rendering.Universal;
|
||||
using UnityEngine.Rendering.Universal.Internal;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
#if HAVE_URP_12_OR_NEWER
|
||||
[DisallowMultipleRendererFeature("Opaque Texture (Rough Refractions)")]
|
||||
#endif
|
||||
public class RoughRefractionFeature : ScriptableRendererFeature
|
||||
{
|
||||
public Downsampling downsampling = Downsampling.None;
|
||||
|
||||
class CustomRenderPass : CopyColorPass
|
||||
{
|
||||
public Downsampling m_DownsamplingMethod;
|
||||
public RenderTargetHandle destination;
|
||||
|
||||
public CustomRenderPass(RenderPassEvent evt) : base(evt,
|
||||
CoreUtils.CreateEngineMaterial(Shader.Find("Hidden/Universal Render Pipeline/Sampling")),
|
||||
CoreUtils.CreateEngineMaterial(Shader.Find("Hidden/Universal Render Pipeline/Blit")))
|
||||
{ }
|
||||
|
||||
public new void Setup(RenderTargetIdentifier source, RenderTargetHandle destination, Downsampling downsampling)
|
||||
{
|
||||
base.Setup(source, destination, downsampling);
|
||||
|
||||
this.destination = destination;
|
||||
this.m_DownsamplingMethod = downsampling;
|
||||
}
|
||||
|
||||
public override void OnCameraSetup(CommandBuffer cmd, ref RenderingData renderingData)
|
||||
{
|
||||
var desc = renderingData.cameraData.cameraTargetDescriptor;
|
||||
desc.useMipMap = true;
|
||||
desc.autoGenerateMips = true;
|
||||
renderingData.cameraData.cameraTargetDescriptor = desc;
|
||||
|
||||
// base.OnCameraSetup(cmd, ref renderingData);
|
||||
|
||||
RenderTextureDescriptor descriptor = renderingData.cameraData.cameraTargetDescriptor;
|
||||
descriptor.msaaSamples = 1;
|
||||
descriptor.depthBufferBits = 0;
|
||||
if (m_DownsamplingMethod == Downsampling._2xBilinear)
|
||||
{
|
||||
descriptor.width /= 2;
|
||||
descriptor.height /= 2;
|
||||
}
|
||||
else if (m_DownsamplingMethod == Downsampling._4xBox || m_DownsamplingMethod == Downsampling._4xBilinear)
|
||||
{
|
||||
descriptor.width /= 4;
|
||||
descriptor.height /= 4;
|
||||
}
|
||||
|
||||
cmd.GetTemporaryRT(destination.id, descriptor, FilterMode.Trilinear);
|
||||
}
|
||||
}
|
||||
|
||||
CustomRenderPass m_ScriptablePass;
|
||||
RenderTargetHandle m_OpaqueColor;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void Create()
|
||||
{
|
||||
m_OpaqueColor.Init("_CameraOpaqueTexture");
|
||||
}
|
||||
|
||||
// Here you can inject one or multiple render passes in the renderer.
|
||||
// This method is called when setting up the renderer once per-camera.
|
||||
public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
|
||||
{
|
||||
if (m_ScriptablePass == null)
|
||||
{
|
||||
m_ScriptablePass = new CustomRenderPass(RenderPassEvent.AfterRenderingSkybox);
|
||||
}
|
||||
m_ScriptablePass.Setup(renderer.cameraColorTarget, m_OpaqueColor, downsampling);
|
||||
|
||||
renderer.EnqueuePass(m_ScriptablePass);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9aa176c7981ee2a469e664fd93f010b5
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "UnityGltf.RenderPipelines",
|
||||
"references": [
|
||||
"GUID:15fc0a57446b3144c949da3e2b9737a9",
|
||||
"GUID:df380645f10b7bc4b97d4f5eb6303d95",
|
||||
"GUID:2bafac87e7f4b9b418d9448d219b01ab"
|
||||
],
|
||||
"includePlatforms": [],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": false,
|
||||
"overrideReferences": true,
|
||||
"precompiledReferences": [],
|
||||
"autoReferenced": false,
|
||||
"defineConstraints": [
|
||||
"UNITY_2020_3_OR_NEWER"
|
||||
],
|
||||
"versionDefines": [
|
||||
{
|
||||
"name": "com.unity.render-pipelines.universal",
|
||||
"expression": "12",
|
||||
"define": "HAVE_URP_12_OR_NEWER"
|
||||
},
|
||||
{
|
||||
"name": "com.unity.render-pipelines.universal",
|
||||
"expression": "10",
|
||||
"define": "HAVE_URP_10_OR_NEWER"
|
||||
}
|
||||
],
|
||||
"noEngineReferences": false
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fe848190f1a690142846fa6384b74e17
|
||||
AssemblyDefinitionImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 61f928488f87d3147ac6bcad15cf6ea1
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 47321deab892e9044bb9d4a193a41208
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a4e5800392410254a94542e26677d4e1
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,207 @@
|
||||
#if UNITY_EDITOR
|
||||
#define ANIMATION_EXPORT_SUPPORTED
|
||||
#endif
|
||||
|
||||
#if ANIMATION_EXPORT_SUPPORTED && (UNITY_ANIMATION || !UNITY_2019_1_OR_NEWER)
|
||||
#define ANIMATION_SUPPORTED
|
||||
#endif
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Animations;
|
||||
using UnityEngine.Playables;
|
||||
using UnityGLTF.Timeline;
|
||||
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public partial class GLTFSceneExporter
|
||||
{
|
||||
#if ANIMATION_SUPPORTED
|
||||
internal void CollectClipCurvesBySampling(GameObject root, AnimationClip clip, Dictionary<string, TargetCurveSet> targetCurves)
|
||||
{
|
||||
var recorder = new GLTFRecorder(root.transform, false, false, false);
|
||||
|
||||
var playableGraph = PlayableGraph.Create();
|
||||
var animationClipPlayable = (Playable) AnimationClipPlayable.Create(playableGraph, clip);
|
||||
|
||||
var rigs = root.GetComponents<IAnimationWindowPreview>();
|
||||
if (rigs != null)
|
||||
{
|
||||
foreach (var rig in rigs)
|
||||
{
|
||||
rig.StopPreview(); // seems to be needed in some cases because the Rig isn't properly marked as non-initialized by Unity
|
||||
rig.StartPreview();
|
||||
animationClipPlayable = rig.BuildPreviewGraph(playableGraph, animationClipPlayable); // modifies the playable to include Animation Rigging data
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
rigs = System.Array.Empty<IAnimationWindowPreview>();
|
||||
}
|
||||
|
||||
var playableOutput = AnimationPlayableOutput.Create(playableGraph, "Animation", root.GetComponent<Animator>());
|
||||
playableOutput.SetSourcePlayable(animationClipPlayable);
|
||||
playableGraph.SetTimeUpdateMode(DirectorUpdateMode.Manual);
|
||||
|
||||
var timeStep = 1.0f / 30.0f;
|
||||
var length = clip.length;
|
||||
var time = 0f;
|
||||
|
||||
#if UNITY_2020_1_OR_NEWER
|
||||
// This seems to not properly cleanup when exporting animation from inside a prefab asset
|
||||
// e.g. when exporting animator with humanoid animation the animator is left disabled after this
|
||||
// the animator is disabled after the first call to `SampleAnimationClip`
|
||||
var driver = ScriptableObject.CreateInstance<AnimationModeDriver>();
|
||||
AnimationMode.StartAnimationMode(driver);
|
||||
#else
|
||||
AnimationMode.StartAnimationMode();
|
||||
#endif
|
||||
AnimationMode.BeginSampling();
|
||||
|
||||
// if this is a Prefab, we need to collect property modifications here to work around
|
||||
// limitations of AnimationMode - otherwise prefab modifications will persist...
|
||||
var isPrefabAsset = PrefabUtility.IsPartOfPrefabAsset(root);
|
||||
var prefabModifications = isPrefabAsset ? PrefabUtility.GetPropertyModifications(root) : default;
|
||||
Undo.RegisterFullObjectHierarchyUndo(root, "Animation Sampling");
|
||||
|
||||
// add the root since we need to shift it around -
|
||||
// it will be reset when exiting AnimationMode again and will not be dirty.
|
||||
AnimationMode_AddTransformTRS(root);
|
||||
|
||||
// TODO not entirely sure if only checking for humanMotion here is correct
|
||||
if (clip.isHumanMotion)
|
||||
{
|
||||
root.transform.localPosition = Vector3.zero;
|
||||
root.transform.localRotation = Quaternion.identity;
|
||||
// root.transform.localScale = Vector3.one;
|
||||
}
|
||||
|
||||
// first frame
|
||||
foreach (var rig in rigs) rig.UpdatePreviewGraph(playableGraph);
|
||||
AnimationMode.SamplePlayableGraph(playableGraph, 0, time);
|
||||
|
||||
// for Animation Rigging its often desired to have one complete loop first, so we need to prewarm to have a nice exportable animation
|
||||
var prewarm = rigs.Length > 0 && clip.isLooping;
|
||||
if (prewarm)
|
||||
{
|
||||
while (time + timeStep < length)
|
||||
{
|
||||
time += timeStep;
|
||||
foreach (var rig in rigs) rig.UpdatePreviewGraph(playableGraph);
|
||||
AnimationMode.SamplePlayableGraph(playableGraph, 0, time);
|
||||
}
|
||||
|
||||
// reset time to the start
|
||||
time = 0;
|
||||
}
|
||||
|
||||
recorder.StartRecording(time);
|
||||
|
||||
while (time + timeStep < length)
|
||||
{
|
||||
time += timeStep;
|
||||
foreach (var rig in rigs) rig.UpdatePreviewGraph(playableGraph);
|
||||
AnimationMode.SamplePlayableGraph(playableGraph, 0, time);
|
||||
recorder.UpdateRecording(time);
|
||||
}
|
||||
|
||||
// last frame
|
||||
time = length;
|
||||
foreach (var rig in rigs) rig.UpdatePreviewGraph(playableGraph);
|
||||
AnimationMode.SamplePlayableGraph(playableGraph, 0, time);
|
||||
recorder.UpdateRecording(time);
|
||||
|
||||
foreach (var rig in rigs) rig.StopPreview();
|
||||
|
||||
AnimationMode.EndSampling();
|
||||
#if UNITY_2020_1_OR_NEWER
|
||||
AnimationMode.StopAnimationMode(driver);
|
||||
#else
|
||||
AnimationMode.StopAnimationMode();
|
||||
#endif
|
||||
|
||||
// reset prefab modifications if this was a prefab asset
|
||||
if (isPrefabAsset) {
|
||||
PrefabUtility.SetPropertyModifications(root, prefabModifications);
|
||||
}
|
||||
|
||||
// seems to be necessary because the animation sampling API doesn't fully work;
|
||||
// sometimes samples still "leak" into property modifications
|
||||
Undo.FlushUndoRecordObjects();
|
||||
Undo.PerformUndo();
|
||||
|
||||
recorder.EndRecording(out var data);
|
||||
if (data == null || !data.Any()) return;
|
||||
|
||||
string CalculatePath(Transform child, Transform parent)
|
||||
{
|
||||
if (child == parent) return "";
|
||||
if (child.parent == null) return "";
|
||||
var parentPath = CalculatePath(child.parent, parent);
|
||||
if (!string.IsNullOrEmpty(parentPath)) return parentPath + "/" + child.name;
|
||||
return child.name;
|
||||
}
|
||||
|
||||
// convert AnimationData back to AnimationCurve (slow)
|
||||
// better would be to directly emit the animation here, but then we need to be careful with partial hierarchies
|
||||
// and other cases that can go wrong.
|
||||
foreach (var kvp in data)
|
||||
{
|
||||
var curveSet = new TargetCurveSet();
|
||||
curveSet.Init();
|
||||
|
||||
var positionTrack = kvp.Value.tracks.FirstOrDefault(x => x.propertyName == "translation");
|
||||
if (positionTrack != null)
|
||||
{
|
||||
var t0 = positionTrack.times;
|
||||
var frameData = positionTrack.values;
|
||||
var posX = new AnimationCurve(t0.Select((value, index) => new Keyframe((float)value, ((Vector3)frameData[index]).x)).ToArray());
|
||||
var posY = new AnimationCurve(t0.Select((value, index) => new Keyframe((float)value, ((Vector3)frameData[index]).y)).ToArray());
|
||||
var posZ = new AnimationCurve(t0.Select((value, index) => new Keyframe((float)value, ((Vector3)frameData[index]).z)).ToArray());
|
||||
curveSet.translationCurves = new [] { posX, posY, posZ };
|
||||
}
|
||||
|
||||
var rotationTrack = kvp.Value.tracks.FirstOrDefault(x => x.propertyName == "rotation");
|
||||
if (rotationTrack != null)
|
||||
{
|
||||
var t1 = rotationTrack.times;
|
||||
var frameData = rotationTrack.values;
|
||||
var rotX = new AnimationCurve(t1.Select((value, index) => new Keyframe((float)value, ((Quaternion)frameData[index]).x)).ToArray());
|
||||
var rotY = new AnimationCurve(t1.Select((value, index) => new Keyframe((float)value, ((Quaternion)frameData[index]).y)).ToArray());
|
||||
var rotZ = new AnimationCurve(t1.Select((value, index) => new Keyframe((float)value, ((Quaternion)frameData[index]).z)).ToArray());
|
||||
var rotW = new AnimationCurve(t1.Select((value, index) => new Keyframe((float)value, ((Quaternion)frameData[index]).w)).ToArray());
|
||||
curveSet.rotationCurves = new [] { rotX, rotY, rotZ, rotW };
|
||||
}
|
||||
|
||||
var scaleTrack = kvp.Value.tracks.FirstOrDefault(x => x.propertyName == "scale");
|
||||
if (scaleTrack != null)
|
||||
{
|
||||
var t2 = scaleTrack.times;
|
||||
var frameData = scaleTrack.values;
|
||||
var sclX = new AnimationCurve(t2.Select((value, index) => new Keyframe((float)value, ((Vector3)frameData[index]).x)).ToArray());
|
||||
var sclY = new AnimationCurve(t2.Select((value, index) => new Keyframe((float)value, ((Vector3)frameData[index]).y)).ToArray());
|
||||
var sclZ = new AnimationCurve(t2.Select((value, index) => new Keyframe((float)value, ((Vector3)frameData[index]).z)).ToArray());
|
||||
curveSet.scaleCurves = new [] { sclX, sclY, sclZ };
|
||||
}
|
||||
|
||||
var calculatedPath = CalculatePath(kvp.Key, root.transform);
|
||||
targetCurves[calculatedPath] = curveSet;
|
||||
}
|
||||
}
|
||||
|
||||
private static MethodInfo _AddTransformTRS;
|
||||
private static void AnimationMode_AddTransformTRS(GameObject gameObject)
|
||||
{
|
||||
if (!gameObject) return;
|
||||
if (_AddTransformTRS == null) _AddTransformTRS = typeof(AnimationMode).GetMethod("AddTransformTRS", (BindingFlags)(-1));
|
||||
_AddTransformTRS?.Invoke(null, new object[] { gameObject, "" });
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 16ea658e76ce4a14b5ef14d825c52147
|
||||
timeCreated: 1662914636
|
||||
@@ -0,0 +1,609 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using GLTF.Schema;
|
||||
using GLTF.Schema.KHR_lights_punctual;
|
||||
using UnityEngine;
|
||||
using UnityGLTF.Extensions;
|
||||
using UnityGLTF.JsonPointer;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public partial class GLTFSceneExporter
|
||||
{
|
||||
internal readonly List<IJsonPointerResolver> pointerResolvers = new List<IJsonPointerResolver>();
|
||||
private readonly KHR_animation_pointer_Resolver animationPointerResolver = new KHR_animation_pointer_Resolver();
|
||||
|
||||
#region Shader Property Names
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
private static readonly int _MainTex = Shader.PropertyToID("_MainTex");
|
||||
private static readonly int _BaseMap = Shader.PropertyToID("_BaseMap");
|
||||
private static readonly int _BaseColorTexture = Shader.PropertyToID("_BaseColorTexture");
|
||||
private static readonly int baseColorTexture = Shader.PropertyToID("baseColorTexture");
|
||||
private static readonly int _EmissionMap = Shader.PropertyToID("_EmissionMap");
|
||||
private static readonly int _EmissiveTexture = Shader.PropertyToID("_EmissiveTexture");
|
||||
private static readonly int emissiveTexture = Shader.PropertyToID("emissiveTexture");
|
||||
private static readonly int _BumpMap = Shader.PropertyToID("_BumpMap");
|
||||
private static readonly int _NormalTexture = Shader.PropertyToID("_NormalTexture");
|
||||
private static readonly int normalTexture = Shader.PropertyToID("normalTexture");
|
||||
private static readonly int _OcclusionMap = Shader.PropertyToID("_OcclusionMap");
|
||||
private static readonly int _OcclusionTexture = Shader.PropertyToID("_OcclusionTexture");
|
||||
private static readonly int occlusionTexture = Shader.PropertyToID("occlusionTexture");
|
||||
|
||||
// ReSharper restore InconsistentNaming
|
||||
#endregion
|
||||
|
||||
public void RegisterResolver(IJsonPointerResolver resolver)
|
||||
{
|
||||
if (!pointerResolvers.Contains(resolver))
|
||||
pointerResolvers.Add(resolver);
|
||||
}
|
||||
|
||||
public void AddAnimationData(Object animatedObject, string propertyName, GLTFAnimation animation, float[] times, object[] values)
|
||||
{
|
||||
if (!animatedObject) return;
|
||||
|
||||
// TODO should skip property switches that are not supported without KHR_animation_pointer
|
||||
// TODO should probably start with the transform check below and stop afterwards if KHR_animation_pointer is off
|
||||
|
||||
if (values.Length <= 0) return;
|
||||
for (var i = 0; i < values.Length; i++)
|
||||
{
|
||||
if (values[i] != null) continue;
|
||||
|
||||
Debug.LogError($"GLTFExporter error: value {i} in animated property \"{propertyName}\" is null. Skipping", animatedObject);
|
||||
return;
|
||||
}
|
||||
|
||||
var channelTargetId = GetIndex(animatedObject);
|
||||
if (channelTargetId < 0)
|
||||
{
|
||||
Debug.LogWarning($"An animated {animatedObject.GetType()} has not been exported, is the object disabled? {animatedObject.name} (InstanceID: {animatedObject.GetInstanceID()})", animatedObject);
|
||||
return;
|
||||
}
|
||||
|
||||
bool flipValueRange = false;
|
||||
float? valueMultiplier = null;
|
||||
bool isTextureTransform = false;
|
||||
bool keepColorAlpha = true;
|
||||
string secondPropertyName = null;
|
||||
string extensionName = null;
|
||||
|
||||
switch (animatedObject)
|
||||
{
|
||||
case Material material:
|
||||
// Debug.Log("material: " + material + ", propertyName: " + propertyName);
|
||||
// mapping from known Unity property names to glTF property names
|
||||
switch (propertyName)
|
||||
{
|
||||
case "_Color":
|
||||
case "_BaseColor":
|
||||
case "_BaseColorFactor":
|
||||
case "baseColorFactor":
|
||||
propertyName = "pbrMetallicRoughness/baseColorFactor";
|
||||
break;
|
||||
case "_Smoothness":
|
||||
case "_Glossiness":
|
||||
propertyName = "pbrMetallicRoughness/roughnessFactor";
|
||||
flipValueRange = true;
|
||||
break;
|
||||
case "_Roughness":
|
||||
case "_RoughnessFactor":
|
||||
case "roughnessFactor":
|
||||
propertyName = "pbrMetallicRoughness/roughnessFactor";
|
||||
break;
|
||||
case "_Metallic":
|
||||
case "_MetallicFactor":
|
||||
case "metallicFactor":
|
||||
propertyName = "pbrMetallicRoughness/metallicFactor";
|
||||
break;
|
||||
case "_MainTex_ST":
|
||||
case "_BaseMap_ST":
|
||||
case "_BaseColorTexture_ST":
|
||||
case "baseColorTexture_ST":
|
||||
if (!(material.HasProperty(_MainTex) && material.GetTexture(_MainTex)) &&
|
||||
!(material.HasProperty(_BaseMap) && material.GetTexture(_BaseMap)) &&
|
||||
!(material.HasProperty(_BaseColorTexture) && material.GetTexture(_BaseColorTexture)) &&
|
||||
!(material.HasProperty(baseColorTexture) && material.GetTexture(baseColorTexture))) return;
|
||||
propertyName = $"pbrMetallicRoughness/baseColorTexture/extensions/{ExtTextureTransformExtensionFactory.EXTENSION_NAME}/{ExtTextureTransformExtensionFactory.SCALE}";
|
||||
secondPropertyName = $"pbrMetallicRoughness/baseColorTexture/extensions/{ExtTextureTransformExtensionFactory.EXTENSION_NAME}/{ExtTextureTransformExtensionFactory.OFFSET}";
|
||||
isTextureTransform = true;
|
||||
extensionName = ExtTextureTransformExtensionFactory.EXTENSION_NAME;
|
||||
break;
|
||||
case "_EmissionColor":
|
||||
case "_EmissiveFactor":
|
||||
case "emissiveFactor":
|
||||
propertyName = "emissiveFactor";
|
||||
secondPropertyName = $"extensions/{KHR_materials_emissive_strength_Factory.EXTENSION_NAME}/{nameof(KHR_materials_emissive_strength.emissiveStrength)}";
|
||||
extensionName = KHR_materials_emissive_strength_Factory.EXTENSION_NAME;
|
||||
keepColorAlpha = false;
|
||||
break;
|
||||
case "_EmissionMap_ST":
|
||||
case "_EmissiveTexture_ST":
|
||||
case "emissiveTexture_ST":
|
||||
if (!(material.HasProperty(_EmissionMap) && material.GetTexture(_EmissionMap)) &&
|
||||
!(material.HasProperty(_EmissiveTexture) && material.GetTexture(_EmissiveTexture)) &&
|
||||
!(material.HasProperty(emissiveTexture) && material.GetTexture(emissiveTexture))) return;
|
||||
propertyName = $"emissiveTexture/extensions/{ExtTextureTransformExtensionFactory.EXTENSION_NAME}/{ExtTextureTransformExtensionFactory.SCALE}";
|
||||
secondPropertyName = $"emissiveTexture/extensions/{ExtTextureTransformExtensionFactory.EXTENSION_NAME}/{ExtTextureTransformExtensionFactory.OFFSET}";
|
||||
isTextureTransform = true;
|
||||
extensionName = ExtTextureTransformExtensionFactory.EXTENSION_NAME;
|
||||
break;
|
||||
case "_Cutoff":
|
||||
case "_AlphaCutoff":
|
||||
case "alphaCutoff":
|
||||
propertyName = "alphaCutoff";
|
||||
break;
|
||||
case "_BumpScale":
|
||||
case "_NormalScale":
|
||||
case "normalScale":
|
||||
case "normalTextureScale":
|
||||
propertyName = "normalTexture/scale";
|
||||
break;
|
||||
case "_BumpMap_ST":
|
||||
case "_NormalTexture_ST":
|
||||
case "normalTexture_ST":
|
||||
if (!(material.HasProperty(_BumpMap) && material.GetTexture(_BumpMap)) &&
|
||||
!(material.HasProperty(_NormalTexture) && material.GetTexture(_NormalTexture)) &&
|
||||
!(material.HasProperty(normalTexture) && material.GetTexture(normalTexture))) return;
|
||||
propertyName = $"normalTexture/extensions/{ExtTextureTransformExtensionFactory.EXTENSION_NAME}/{ExtTextureTransformExtensionFactory.SCALE}";
|
||||
secondPropertyName = $"normalTexture/extensions/{ExtTextureTransformExtensionFactory.EXTENSION_NAME}/{ExtTextureTransformExtensionFactory.OFFSET}";
|
||||
isTextureTransform = true;
|
||||
extensionName = ExtTextureTransformExtensionFactory.EXTENSION_NAME;
|
||||
break;
|
||||
case "_OcclusionStrength":
|
||||
case "occlusionStrength":
|
||||
case "occlusionTextureStrength":
|
||||
propertyName = "occlusionTexture/strength";
|
||||
break;
|
||||
case "_OcclusionMap_ST":
|
||||
case "_OcclusionTexture_ST":
|
||||
case "occlusionTexture_ST":
|
||||
if (!(material.HasProperty(_OcclusionMap) && material.GetTexture(_OcclusionMap)) &&
|
||||
!(material.HasProperty(_OcclusionTexture) && material.GetTexture(_OcclusionTexture)) &&
|
||||
!(material.HasProperty(occlusionTexture) && material.GetTexture(occlusionTexture))) return;
|
||||
propertyName = $"occlusionTexture/extensions/{ExtTextureTransformExtensionFactory.EXTENSION_NAME}/{ExtTextureTransformExtensionFactory.SCALE}";
|
||||
secondPropertyName = $"occlusionTexture/extensions/{ExtTextureTransformExtensionFactory.EXTENSION_NAME}/{ExtTextureTransformExtensionFactory.OFFSET}";
|
||||
isTextureTransform = true;
|
||||
extensionName = ExtTextureTransformExtensionFactory.EXTENSION_NAME;
|
||||
break;
|
||||
|
||||
// TODO metallic/roughness _ST
|
||||
|
||||
// KHR_materials_transmission
|
||||
case "_TransmissionFactor":
|
||||
case "transmissionFactor":
|
||||
propertyName = $"extensions/{KHR_materials_transmission_Factory.EXTENSION_NAME}/{nameof(KHR_materials_transmission.transmissionFactor)}";
|
||||
extensionName = KHR_materials_transmission_Factory.EXTENSION_NAME;
|
||||
break;
|
||||
|
||||
// KHR_materials_volume
|
||||
case "_ThicknessFactor":
|
||||
case "thicknessFactor":
|
||||
propertyName = $"extensions/{KHR_materials_volume_Factory.EXTENSION_NAME}/{nameof(KHR_materials_volume.thicknessFactor)}";
|
||||
extensionName = KHR_materials_volume_Factory.EXTENSION_NAME;
|
||||
break;
|
||||
case "_AttenuationDistance":
|
||||
case "attenuationDistance":
|
||||
propertyName = $"extensions/{KHR_materials_volume_Factory.EXTENSION_NAME}/{nameof(KHR_materials_volume.attenuationDistance)}";
|
||||
extensionName = KHR_materials_volume_Factory.EXTENSION_NAME;
|
||||
break;
|
||||
case "_AttenuationColor":
|
||||
case "attenuationColor":
|
||||
propertyName = $"extensions/{KHR_materials_volume_Factory.EXTENSION_NAME}/{nameof(KHR_materials_volume.attenuationColor)}";
|
||||
extensionName = KHR_materials_volume_Factory.EXTENSION_NAME;
|
||||
keepColorAlpha = false;
|
||||
break;
|
||||
|
||||
// KHR_materials_ior
|
||||
case "_IOR":
|
||||
case "ior":
|
||||
propertyName = $"extensions/{KHR_materials_ior_Factory.EXTENSION_NAME}/{nameof(KHR_materials_ior.ior)}";
|
||||
extensionName = KHR_materials_ior_Factory.EXTENSION_NAME;
|
||||
break;
|
||||
|
||||
// KHR_materials_iridescence
|
||||
case "_IridescenceFactor":
|
||||
case "iridescenceFactor":
|
||||
propertyName = $"extensions/{KHR_materials_iridescence_Factory.EXTENSION_NAME}/{nameof(KHR_materials_iridescence.iridescenceFactor)}";
|
||||
extensionName = KHR_materials_iridescence_Factory.EXTENSION_NAME;
|
||||
break;
|
||||
case "_IridescenceIor":
|
||||
case "iridescenceIor":
|
||||
propertyName = $"extensions/{KHR_materials_iridescence_Factory.EXTENSION_NAME}/{nameof(KHR_materials_iridescence.iridescenceIor)}";
|
||||
extensionName = KHR_materials_iridescence_Factory.EXTENSION_NAME;
|
||||
break;
|
||||
case "_IridescenceThicknessMinimum":
|
||||
case "iridescenceThicknessMinimum":
|
||||
propertyName = $"extensions/{KHR_materials_iridescence_Factory.EXTENSION_NAME}/{nameof(KHR_materials_iridescence.iridescenceThicknessMinimum)}";
|
||||
extensionName = KHR_materials_iridescence_Factory.EXTENSION_NAME;
|
||||
break;
|
||||
case "_IridescenceThicknessMaximum":
|
||||
case "iridescenceThicknessMaximum":
|
||||
propertyName = $"extensions/{KHR_materials_iridescence_Factory.EXTENSION_NAME}/{nameof(KHR_materials_iridescence.iridescenceThicknessMaximum)}";
|
||||
extensionName = KHR_materials_iridescence_Factory.EXTENSION_NAME;
|
||||
break;
|
||||
|
||||
// KHR_materials_specular
|
||||
case "_SpecularFactor":
|
||||
case "specularFactor":
|
||||
propertyName = $"extensions/{KHR_materials_specular_Factory.EXTENSION_NAME}/{nameof(KHR_materials_specular.specularFactor)}";
|
||||
extensionName = KHR_materials_specular_Factory.EXTENSION_NAME;
|
||||
break;
|
||||
case "_SpecularColorFactor":
|
||||
case "specularColorFactor":
|
||||
propertyName = $"extensions/{KHR_materials_specular_Factory.EXTENSION_NAME}/{nameof(KHR_materials_specular.specularColorFactor)}";
|
||||
extensionName = KHR_materials_specular_Factory.EXTENSION_NAME;
|
||||
keepColorAlpha = false;
|
||||
break;
|
||||
|
||||
// TODO KHR_materials_clearcoat
|
||||
// case "_ClearcoatFactor":
|
||||
// case "clearcoatFactor":
|
||||
// propertyName = $"extensions/{KHR_materials_clearcoat_Factory.EXTENSION_NAME}/{nameof(KHR_materials_clearcoat.clearcoatFactor)}";
|
||||
// extensionName = KHR_materials_clearcoat_Factory.EXTENSION_NAME;
|
||||
// break;
|
||||
// case "_ClearcoatRoughnessFactor":
|
||||
// case "clearcoatRoughnessFactor":
|
||||
// propertyName = $"extensions/{KHR_materials_clearcoat_Factory.EXTENSION_NAME}/{nameof(KHR_materials_clearcoat.clearcoatRoughnessFactor)}";
|
||||
// extensionName = KHR_materials_clearcoat_Factory.EXTENSION_NAME;
|
||||
// break;
|
||||
|
||||
// TODO KHR_materials_sheen
|
||||
// case "_SheenColorFactor":
|
||||
// case "sheenColorFactor":
|
||||
// propertyName = $"extensions/{KHR_materials_sheen_Factory.EXTENSION_NAME}/{nameof(KHR_materials_sheen.sheenColorFactor)}";
|
||||
// extensionName = KHR_materials_sheen_Factory.EXTENSION_NAME;
|
||||
// keepColorAlpha = false;
|
||||
// break;
|
||||
// case "_SheenRoughnessFactor":
|
||||
// case "sheenRoughnessFactor":
|
||||
// propertyName = $"extensions/{KHR_materials_sheen_Factory.EXTENSION_NAME}/{nameof(KHR_materials_sheen.sheenRoughnessFactor)}";
|
||||
// extensionName = KHR_materials_sheen_Factory.EXTENSION_NAME;
|
||||
// break;
|
||||
default:
|
||||
Debug.Log(LogType.Warning, "Unknown property name on Material " + material + ": " + propertyName);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case Light light:
|
||||
extensionName = KHR_lights_punctualExtensionFactory.EXTENSION_NAME;
|
||||
switch (propertyName)
|
||||
{
|
||||
case "m_Color":
|
||||
propertyName = $"color";
|
||||
keepColorAlpha = false;
|
||||
break;
|
||||
case "m_Intensity":
|
||||
valueMultiplier = Mathf.PI; // matches ExportLight
|
||||
propertyName = $"intensity";
|
||||
break;
|
||||
case "m_SpotAngle":
|
||||
valueMultiplier = Mathf.Deg2Rad / 2;
|
||||
propertyName = $"spot/outerConeAngle";
|
||||
break;
|
||||
case "m_InnerSpotAngle":
|
||||
valueMultiplier = Mathf.Deg2Rad / 2;
|
||||
propertyName = $"spot/innerConeAngle";
|
||||
break;
|
||||
case "m_Range":
|
||||
propertyName = "range";
|
||||
break;
|
||||
default:
|
||||
extensionName = null;
|
||||
Debug.Log(LogType.Warning, "Unknown property name on Light " + light + ": " + propertyName);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case Camera camera:
|
||||
if(camera.orthographic)
|
||||
{
|
||||
switch (propertyName)
|
||||
{
|
||||
case "orthographic size":
|
||||
// TODO conversion factor
|
||||
propertyName = "orthographic/ymag";
|
||||
secondPropertyName = "orthographic/xmag";
|
||||
break;
|
||||
case "near clip plane":
|
||||
propertyName = "orthographic/znear";
|
||||
break;
|
||||
case "far clip plane":
|
||||
propertyName = "orthographic/zfar";
|
||||
break;
|
||||
default:
|
||||
Debug.Log(LogType.Warning, "Unknown property name on Camera " + camera + ": " + propertyName);
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (propertyName)
|
||||
{
|
||||
case "field of view":
|
||||
// TODO conversion factor
|
||||
propertyName = "perspective/yfov";
|
||||
valueMultiplier = Mathf.Deg2Rad;
|
||||
break;
|
||||
case "near clip plane":
|
||||
propertyName = "perspective/znear";
|
||||
break;
|
||||
case "far clip plane":
|
||||
propertyName = "perspective/zfar";
|
||||
break;
|
||||
default:
|
||||
Debug.Log(LogType.Warning, "Unknown property name on Camera " + camera + ": " + propertyName);
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case SkinnedMeshRenderer skinnedMesh:
|
||||
// this code is adapted from SkinnedMeshRendererEditor (which calculates the right range for sliders to show)
|
||||
// instead of calculating per blend shape, we're assuming all blendshapes have the same min/max here though.
|
||||
var minBlendShapeFrameWeight = 0.0f;
|
||||
var maxBlendShapeFrameWeight = 0.0f;
|
||||
|
||||
var sharedMesh = skinnedMesh.sharedMesh;
|
||||
if (!sharedMesh)
|
||||
{
|
||||
Debug.Log(LogType.Error, "No mesh on SkinnedMeshRenderer " + skinnedMesh + ", skipping animation");
|
||||
return;
|
||||
}
|
||||
|
||||
var shapeCount = sharedMesh.blendShapeCount;
|
||||
for (int index = 0; index < shapeCount; ++index)
|
||||
{
|
||||
var blendShapeFrameCount = sharedMesh.GetBlendShapeFrameCount(index);
|
||||
for (var frameIndex = 0; frameIndex < blendShapeFrameCount; ++frameIndex)
|
||||
{
|
||||
var shapeFrameWeight = sharedMesh.GetBlendShapeFrameWeight(index, frameIndex);
|
||||
minBlendShapeFrameWeight = Mathf.Min(shapeFrameWeight, minBlendShapeFrameWeight);
|
||||
maxBlendShapeFrameWeight = Mathf.Max(shapeFrameWeight, maxBlendShapeFrameWeight);
|
||||
}
|
||||
}
|
||||
|
||||
if (maxBlendShapeFrameWeight != 0)
|
||||
valueMultiplier = 1.0f / maxBlendShapeFrameWeight;
|
||||
|
||||
break;
|
||||
case Transform _:
|
||||
// generally allowed and already in the right format
|
||||
break;
|
||||
default:
|
||||
// propertyName is exported as-is
|
||||
// Debug.LogWarning($"Implicitly handling animated property \"{propertyName}\" for target {animatedObject}", animatedObject);
|
||||
|
||||
// filtering for what to include / what not to include based on whether its target can be resolved
|
||||
if (settings.UseAnimationPointer && animatedObject is Component _)
|
||||
{
|
||||
var couldResolve = false;
|
||||
var prop = $"/nodes/{channelTargetId}/{propertyName}";
|
||||
foreach (var res in pointerResolvers)
|
||||
{
|
||||
// TODO: ideally we have a new method here to just ask the resolver if it supports that type
|
||||
if (res.TryResolve(animatedObject, ref prop))
|
||||
{
|
||||
couldResolve = true;
|
||||
}
|
||||
}
|
||||
if (!couldResolve)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
var Node = new NodeId
|
||||
{
|
||||
Id = channelTargetId,
|
||||
Root = _root
|
||||
};
|
||||
|
||||
AccessorId timeAccessor = ExportAccessor(times);
|
||||
|
||||
AnimationChannel Tchannel = new AnimationChannel();
|
||||
AnimationChannelTarget TchannelTarget = new AnimationChannelTarget() { Path = propertyName, Node = Node };
|
||||
Tchannel.Target = TchannelTarget;
|
||||
|
||||
AnimationSampler Tsampler = new AnimationSampler();
|
||||
Tsampler.Input = timeAccessor;
|
||||
|
||||
// for cases where one property needs to be split up into multiple tracks
|
||||
// example: emissiveFactor * emissiveStrength
|
||||
// TODO not needed when secondPropertyName==null
|
||||
AnimationChannel Tchannel2 = new AnimationChannel();
|
||||
AnimationChannelTarget TchannelTarget2 = new AnimationChannelTarget() { Path = secondPropertyName, Node = Node };
|
||||
Tchannel2.Target = TchannelTarget2;
|
||||
AnimationSampler Tsampler2 = new AnimationSampler();
|
||||
Tsampler2.Input = timeAccessor;
|
||||
bool actuallyNeedSecondSampler = true;
|
||||
|
||||
var val = values[0];
|
||||
switch (val)
|
||||
{
|
||||
case float _:
|
||||
if (flipValueRange)
|
||||
{
|
||||
Tsampler.Output = ExportAccessor(Array.ConvertAll(values, e => 1.0f - (float)e));
|
||||
}
|
||||
else if (valueMultiplier.HasValue)
|
||||
{
|
||||
var multiplier = valueMultiplier.Value;
|
||||
Tsampler.Output = ExportAccessor(Array.ConvertAll(values, e => ((float)e) * multiplier));
|
||||
}
|
||||
else
|
||||
{
|
||||
Tsampler.Output = ExportAccessor(Array.ConvertAll(values, e => (float)e));
|
||||
|
||||
if (propertyName == "orthographic/ymag")
|
||||
{
|
||||
Tsampler2.Output = Tsampler.Output;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case float[] _:
|
||||
// check that all entries have the same length using a for loop
|
||||
var firstLength = ((float[])values[0]).Length;
|
||||
for (var i = 1; i < values.Length; i++)
|
||||
{
|
||||
if (((float[])values[i]).Length == firstLength) continue;
|
||||
|
||||
Debug.Log(LogType.Error, "When animating float arrays, all array entries must have the same length. Skipping");
|
||||
return;
|
||||
}
|
||||
|
||||
// construct a float array of all the float arrays together
|
||||
var floatArray = new float[values.Length * firstLength];
|
||||
|
||||
// copy the individual arrays into the float array using Array.Copy
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
Array.Copy((float[])values[i], 0, floatArray, i * firstLength, firstLength);
|
||||
|
||||
// glTF weights 0..1 match to Unity weights 0..100, but Unity weights can be in arbitrary ranges
|
||||
if (valueMultiplier.HasValue)
|
||||
{
|
||||
for (var i = 0; i < floatArray.Length; i++)
|
||||
floatArray[i] *= valueMultiplier.Value;
|
||||
}
|
||||
|
||||
Tsampler.Output = ExportAccessor(floatArray);
|
||||
break;
|
||||
case Vector2 _:
|
||||
Tsampler.Output = ExportAccessor(Array.ConvertAll(values, e => (Vector2)e));
|
||||
break;
|
||||
case Vector3 _:
|
||||
if (propertyName == "translation")
|
||||
Tsampler.Output = ExportAccessor(Array.ConvertAll(values, e =>
|
||||
{
|
||||
var v = (Vector3)e;
|
||||
v.Scale(new Vector3(-1, 1, 1));
|
||||
return v;
|
||||
}));
|
||||
else
|
||||
Tsampler.Output = ExportAccessor(Array.ConvertAll(values, e => (Vector3)e));
|
||||
break;
|
||||
case Vector4 _:
|
||||
if (!isTextureTransform)
|
||||
{
|
||||
Tsampler.Output = ExportAccessor(Array.ConvertAll(values, e => (Vector4)e));
|
||||
}
|
||||
else
|
||||
{
|
||||
var scales = new Vector2[values.Length];
|
||||
var offsets = new Vector2[values.Length];
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
{
|
||||
DecomposeScaleOffset((Vector4) values[i], out var scale, out var offset);
|
||||
scales[i] = scale;
|
||||
offsets[i] = offset;
|
||||
}
|
||||
Tsampler.Output = ExportAccessor(scales);
|
||||
Tsampler2.Output = ExportAccessor(offsets);
|
||||
}
|
||||
break;
|
||||
case Quaternion _:
|
||||
var animatedNode = _root.Nodes[channelTargetId];
|
||||
var needsFlippedLookDirection = animatedNode.Light != null || animatedNode.Camera != null;
|
||||
Tsampler.Output = ExportAccessorSwitchHandedness(Array.ConvertAll(values, e => (Quaternion)e), needsFlippedLookDirection); // Vec4 for rotations
|
||||
break;
|
||||
case Color _:
|
||||
if (propertyName == "emissiveFactor" && secondPropertyName != null)
|
||||
{
|
||||
var colors = new Color[values.Length];
|
||||
var strengths = new float[values.Length];
|
||||
actuallyNeedSecondSampler = false;
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
{
|
||||
DecomposeEmissionColor((Color) values[i], out var color, out var intensity);
|
||||
colors[i] = color;
|
||||
strengths[i] = intensity;
|
||||
if (intensity > 1)
|
||||
actuallyNeedSecondSampler = true;
|
||||
}
|
||||
Tsampler.Output = ExportAccessor(colors, false);
|
||||
Tsampler2.Output = ExportAccessor(strengths);
|
||||
}
|
||||
else
|
||||
{
|
||||
Tsampler.Output = ExportAccessor(Array.ConvertAll(values, e => (Color)e), keepColorAlpha);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (Tsampler.Output != null) Tsampler.Output.Value.BufferView.Value.ByteStride = 0;
|
||||
if (Tsampler2.Output != null) Tsampler2.Output.Value.BufferView.Value.ByteStride = 0;
|
||||
|
||||
if (Tsampler.Output == null)
|
||||
{
|
||||
Debug.LogError($"GLTFExporter: Something went wrong, empty sampler output for \"{propertyName}\" in {animatedObject}", animatedObject);
|
||||
return;
|
||||
}
|
||||
|
||||
Tchannel.Sampler = new AnimationSamplerId
|
||||
{
|
||||
Id = animation.Samplers.Count,
|
||||
GLTFAnimation = animation,
|
||||
Root = _root
|
||||
};
|
||||
animation.Samplers.Add(Tsampler);
|
||||
animation.Channels.Add(Tchannel);
|
||||
|
||||
if (settings.UseAnimationPointer)
|
||||
ConvertToAnimationPointer(animatedObject, propertyName, TchannelTarget);
|
||||
|
||||
// in some cases, extensions aren't required even when we think they might, e.g. for emission color animation.
|
||||
// if all animated values are below 1, we don't need a separate channel for emissive_intensity.
|
||||
if (!actuallyNeedSecondSampler)
|
||||
{
|
||||
extensionName = null;
|
||||
secondPropertyName = null;
|
||||
}
|
||||
|
||||
if (extensionName != null)
|
||||
{
|
||||
DeclareExtensionUsage(extensionName, false);
|
||||
|
||||
// add extension to material if needed
|
||||
if(animatedObject is Material material)
|
||||
{
|
||||
var mat = GetMaterialId(_root, material);
|
||||
if (mat.Value.Extensions == null || !mat.Value.Extensions.ContainsKey(extensionName))
|
||||
{
|
||||
mat.Value.AddExtension(extensionName, GLTFProperty.CreateEmptyExtension(extensionName));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (secondPropertyName != null)
|
||||
{
|
||||
Tchannel2.Sampler = new AnimationSamplerId
|
||||
{
|
||||
Id = animation.Samplers.Count,
|
||||
GLTFAnimation = animation,
|
||||
Root = _root
|
||||
};
|
||||
animation.Samplers.Add(Tsampler2);
|
||||
animation.Channels.Add(Tchannel2);
|
||||
|
||||
if (settings.UseAnimationPointer)
|
||||
ConvertToAnimationPointer(animatedObject, secondPropertyName, TchannelTarget2);
|
||||
}
|
||||
}
|
||||
|
||||
void ConvertToAnimationPointer(object animatedObject, string propertyName, AnimationChannelTarget target)
|
||||
{
|
||||
var ext = new KHR_animation_pointer();
|
||||
ext.propertyBinding = propertyName;
|
||||
ext.animatedObject = animatedObject;
|
||||
ext.channel = target;
|
||||
animationPointerResolver.Add(ext);
|
||||
|
||||
target.Node = null;
|
||||
target.Path = "pointer";
|
||||
target.AddExtension(KHR_animation_pointer.EXTENSION_NAME, ext);
|
||||
DeclareExtensionUsage(KHR_animation_pointer.EXTENSION_NAME, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 23441437ac77a884d83d8ae32ae8b705
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,77 @@
|
||||
using System.Collections.Generic;
|
||||
using GLTF.Schema;
|
||||
using UnityEngine;
|
||||
using CameraType = GLTF.Schema.CameraType;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public partial class GLTFSceneExporter
|
||||
{
|
||||
private Dictionary<int, int> _exportedCameras;
|
||||
|
||||
private CameraId ExportCamera(Camera unityCamera)
|
||||
{
|
||||
GLTFCamera camera = new GLTFCamera();
|
||||
//name
|
||||
camera.Name = unityCamera.name;
|
||||
|
||||
//type
|
||||
bool isOrthographic = unityCamera.orthographic;
|
||||
camera.Type = isOrthographic ? CameraType.orthographic : CameraType.perspective;
|
||||
Matrix4x4 matrix = unityCamera.projectionMatrix;
|
||||
|
||||
//matrix properties: compute the fields from the projection matrix
|
||||
if (isOrthographic)
|
||||
{
|
||||
CameraOrthographic ortho = new CameraOrthographic();
|
||||
|
||||
ortho.XMag = 1 / matrix[0, 0];
|
||||
ortho.YMag = 1 / matrix[1, 1];
|
||||
|
||||
float farClip = (matrix[2, 3] / matrix[2, 2]) - (1 / matrix[2, 2]);
|
||||
float nearClip = farClip + (2 / matrix[2, 2]);
|
||||
ortho.ZFar = farClip;
|
||||
ortho.ZNear = nearClip;
|
||||
|
||||
camera.Orthographic = ortho;
|
||||
}
|
||||
else
|
||||
{
|
||||
CameraPerspective perspective = new CameraPerspective();
|
||||
float fov = 2 * Mathf.Atan(1 / matrix[1, 1]);
|
||||
float aspectRatio = matrix[1, 1] / matrix[0, 0];
|
||||
perspective.YFov = fov;
|
||||
perspective.AspectRatio = aspectRatio;
|
||||
|
||||
if (matrix[2, 2] == -1)
|
||||
{
|
||||
//infinite projection matrix
|
||||
float nearClip = matrix[2, 3] * -0.5f;
|
||||
perspective.ZNear = nearClip;
|
||||
}
|
||||
else
|
||||
{
|
||||
//finite projection matrix
|
||||
float farClip = matrix[2, 3] / (matrix[2, 2] + 1);
|
||||
float nearClip = farClip * (matrix[2, 2] + 1) / (matrix[2, 2] - 1);
|
||||
perspective.ZFar = farClip;
|
||||
perspective.ZNear = nearClip;
|
||||
}
|
||||
camera.Perspective = perspective;
|
||||
}
|
||||
|
||||
var id = new CameraId
|
||||
{
|
||||
Id = _root.Cameras.Count,
|
||||
Root = _root
|
||||
};
|
||||
|
||||
// Register nodes for animation parsing (could be disabled if animation is disabled)
|
||||
_exportedCameras.Add(unityCamera.GetInstanceID(), _root.Cameras.Count);
|
||||
_root.Cameras.Add(camera);
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 44a8dfd50fa642f4baf09232690eeab2
|
||||
timeCreated: 1657013996
|
||||
@@ -0,0 +1,87 @@
|
||||
using System.Collections.Generic;
|
||||
using GLTF.Schema;
|
||||
using GLTF.Schema.KHR_lights_punctual;
|
||||
using UnityEngine;
|
||||
using LightType = UnityEngine.LightType;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public partial class GLTFSceneExporter
|
||||
{
|
||||
private Dictionary<int, int> _exportedLights;
|
||||
|
||||
private LightId ExportLight(Light unityLight)
|
||||
{
|
||||
GLTFLight light = null;
|
||||
|
||||
if (unityLight.type == LightType.Spot)
|
||||
{
|
||||
// TODO URP/HDRP can distinguish here, no need to guess innerConeAngle there
|
||||
light = new GLTFSpotLight() { innerConeAngle = unityLight.spotAngle / 2 * Mathf.Deg2Rad * 0.8f, outerConeAngle = unityLight.spotAngle / 2 * Mathf.Deg2Rad };
|
||||
light.Name = unityLight.name;
|
||||
|
||||
light.type = unityLight.type.ToString().ToLower();
|
||||
light.color = new GLTF.Math.Color(unityLight.color.r, unityLight.color.g, unityLight.color.b, 1);
|
||||
light.range = unityLight.range;
|
||||
light.intensity = unityLight.intensity * Mathf.PI;
|
||||
}
|
||||
else if (unityLight.type == LightType.Directional)
|
||||
{
|
||||
light = new GLTFDirectionalLight();
|
||||
light.Name = unityLight.name;
|
||||
|
||||
light.type = unityLight.type.ToString().ToLower();
|
||||
light.color = new GLTF.Math.Color(unityLight.color.r, unityLight.color.g, unityLight.color.b, 1);
|
||||
light.intensity = unityLight.intensity * Mathf.PI;
|
||||
}
|
||||
else if (unityLight.type == LightType.Point)
|
||||
{
|
||||
light = new GLTFPointLight();
|
||||
light.Name = unityLight.name;
|
||||
|
||||
light.type = unityLight.type.ToString().ToLower();
|
||||
light.color = new GLTF.Math.Color(unityLight.color.r, unityLight.color.g, unityLight.color.b, 1);
|
||||
light.range = unityLight.range;
|
||||
light.intensity = unityLight.intensity * Mathf.PI;
|
||||
}
|
||||
else
|
||||
{
|
||||
// unknown light type, we shouldn't export this
|
||||
|
||||
// light = new GLTFLight();
|
||||
// light.Name = unityLight.name;
|
||||
// light.type = unityLight.type.ToString().ToLower();
|
||||
// light.color = new GLTF.Math.Color(unityLight.color.r, unityLight.color.g, unityLight.color.b, 1);
|
||||
}
|
||||
|
||||
if (light != null)
|
||||
{
|
||||
DeclareExtensionUsage(KHR_lights_punctualExtensionFactory.EXTENSION_NAME, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogWarning(null, $"Light couldn't be exported: {unityLight.name}. The type may be unsupported in glTF ({unityLight.type})", unityLight.gameObject);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (_root.Lights == null)
|
||||
{
|
||||
_root.Lights = new List<GLTFLight>();
|
||||
}
|
||||
|
||||
var id = new LightId
|
||||
{
|
||||
Id = _root.Lights.Count,
|
||||
Root = _root
|
||||
};
|
||||
|
||||
// Register nodes for animation parsing (could be disabled if animation is disabled)
|
||||
_exportedLights.Add(unityLight.GetInstanceID(), _root.Lights.Count);
|
||||
|
||||
//list of lightids should be in extensions object
|
||||
_root.Lights.Add(light);
|
||||
|
||||
return id;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 122e3cac6af1417c88b9cb6b6d91b933
|
||||
timeCreated: 1657013984
|
||||
@@ -0,0 +1,933 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using GLTF.Schema;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
using UnityGLTF.Extensions;
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public partial class GLTFSceneExporter
|
||||
{
|
||||
/// <returns>True: material export is complete. False: continue regular export.</returns>
|
||||
public delegate bool BeforeMaterialExportDelegate(GLTFSceneExporter exporter, GLTFRoot gltfRoot, Material material, GLTFMaterial materialNode);
|
||||
public delegate void AfterMaterialExportDelegate(GLTFSceneExporter exporter, GLTFRoot gltfRoot, Material material, GLTFMaterial materialNode);
|
||||
|
||||
// Static callbacks
|
||||
public static event BeforeSceneExportDelegate BeforeSceneExport;
|
||||
public static event AfterSceneExportDelegate AfterSceneExport;
|
||||
public static event AfterNodeExportDelegate AfterNodeExport;
|
||||
/// <returns>True: material export is complete. False: continue regular export.</returns>
|
||||
public static event BeforeMaterialExportDelegate BeforeMaterialExport;
|
||||
public static event AfterMaterialExportDelegate AfterMaterialExport;
|
||||
|
||||
// mock for Default material
|
||||
private static Material _defaultMaterial = null;
|
||||
public static Material DefaultMaterial
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_defaultMaterial) return _defaultMaterial;
|
||||
|
||||
#if UNITY_2019_3_OR_NEWER
|
||||
var pipelineAsset = GraphicsSettings.currentRenderPipeline;
|
||||
if (pipelineAsset)
|
||||
{
|
||||
_defaultMaterial = pipelineAsset.defaultMaterial;
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
var shader = Shader.Find("Legacy Shaders/Diffuse"); // by default in the always included shaders list
|
||||
if (shader)
|
||||
_defaultMaterial = new Material(shader);
|
||||
}
|
||||
return _defaultMaterial;
|
||||
}
|
||||
}
|
||||
|
||||
public MaterialId ExportMaterial(Material materialObj)
|
||||
{
|
||||
MaterialId id = GetMaterialId(_root, materialObj);
|
||||
if (id != null)
|
||||
{
|
||||
return id;
|
||||
}
|
||||
|
||||
var material = new GLTFMaterial();
|
||||
|
||||
if (!materialObj)
|
||||
{
|
||||
if (ExportNames)
|
||||
{
|
||||
material.Name = "default";
|
||||
}
|
||||
|
||||
// create default material
|
||||
// TODO check why we need to do anything here
|
||||
material.PbrMetallicRoughness = new PbrMetallicRoughness() { MetallicFactor = 0, RoughnessFactor = 1.0f };
|
||||
return CreateAndAddMaterialId(materialObj, material);
|
||||
}
|
||||
|
||||
if (ExportNames)
|
||||
{
|
||||
material.Name = materialObj.name;
|
||||
}
|
||||
|
||||
// before material export: only continue with regular export if that didn't succeed.
|
||||
if (_exportOptions.BeforeMaterialExport != null)
|
||||
{
|
||||
beforeMaterialExportMarker.Begin();
|
||||
if (_exportOptions.BeforeMaterialExport.Invoke(this, _root, materialObj, material))
|
||||
{
|
||||
beforeMaterialExportMarker.End();
|
||||
return CreateAndAddMaterialId(materialObj, material);
|
||||
}
|
||||
else
|
||||
{
|
||||
beforeMaterialExportMarker.End();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// static callback, run after options callback
|
||||
// we're iterating here because we want to stop calling any once we hit one that can export this material.
|
||||
if (BeforeMaterialExport != null)
|
||||
{
|
||||
var list = BeforeMaterialExport.GetInvocationList();
|
||||
foreach (var entry in list)
|
||||
{
|
||||
beforeMaterialExportMarker.Begin();
|
||||
var cb = (BeforeMaterialExportDelegate) entry;
|
||||
if (cb != null && cb.Invoke(this, _root, materialObj, material))
|
||||
{
|
||||
beforeMaterialExportMarker.End();
|
||||
return CreateAndAddMaterialId(materialObj, material);
|
||||
}
|
||||
else
|
||||
{
|
||||
beforeMaterialExportMarker.End();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
exportMaterialMarker.Begin();
|
||||
var isBirp =
|
||||
#if UNITY_2019_3_OR_NEWER
|
||||
!GraphicsSettings.currentRenderPipeline;
|
||||
#else
|
||||
true;
|
||||
#endif
|
||||
|
||||
switch (materialObj.GetTag("RenderType", false, ""))
|
||||
{
|
||||
case "TransparentCutout":
|
||||
if (materialObj.HasProperty("alphaCutoff"))
|
||||
material.AlphaCutoff = materialObj.GetFloat("alphaCutoff");
|
||||
else if (materialObj.HasProperty("_AlphaCutoff"))
|
||||
material.AlphaCutoff = materialObj.GetFloat("_AlphaCutoff");
|
||||
else if (materialObj.HasProperty("_Cutoff"))
|
||||
material.AlphaCutoff = materialObj.GetFloat("_Cutoff");
|
||||
material.AlphaMode = AlphaMode.MASK;
|
||||
break;
|
||||
case "Transparent":
|
||||
case "Fade":
|
||||
material.AlphaMode = AlphaMode.BLEND;
|
||||
break;
|
||||
default:
|
||||
if ((!isBirp && materialObj.IsKeywordEnabled("_ALPHATEST_ON")) ||
|
||||
(isBirp && materialObj.IsKeywordEnabled("_BUILTIN_ALPHATEST_ON")) ||
|
||||
materialObj.renderQueue == 2450)
|
||||
{
|
||||
if (materialObj.HasProperty("alphaCutoff"))
|
||||
material.AlphaCutoff = materialObj.GetFloat("alphaCutoff");
|
||||
else if (materialObj.HasProperty("_AlphaCutoff"))
|
||||
material.AlphaCutoff = materialObj.GetFloat("_AlphaCutoff");
|
||||
else if (materialObj.HasProperty("_Cutoff"))
|
||||
material.AlphaCutoff = materialObj.GetFloat("_Cutoff");
|
||||
material.AlphaMode = AlphaMode.MASK;
|
||||
}
|
||||
else
|
||||
{
|
||||
material.AlphaMode = AlphaMode.OPAQUE;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
material.DoubleSided = (materialObj.HasProperty("_Cull") && materialObj.GetInt("_Cull") == (int)CullMode.Off) ||
|
||||
(materialObj.HasProperty("_CullMode") && materialObj.GetInt("_CullMode") == (int)CullMode.Off) ||
|
||||
(materialObj.shader.name.EndsWith("-Double")); // workaround for exporting shaders that are set to double-sided on 2020.3
|
||||
|
||||
if (materialObj.IsKeywordEnabled("_EMISSION") || materialObj.IsKeywordEnabled("EMISSION") || materialObj.HasProperty("emissiveTexture") || materialObj.HasProperty("_EmissiveTexture"))
|
||||
{
|
||||
if (materialObj.HasProperty("_EmissionColor") || materialObj.HasProperty("emissiveFactor") || materialObj.HasProperty("_EmissiveFactor"))
|
||||
{
|
||||
var c = materialObj.HasProperty("_EmissionColor") ? materialObj.GetColor("_EmissionColor") : materialObj.HasProperty("emissiveFactor") ? materialObj.GetColor("emissiveFactor") : materialObj.GetColor("_EmissiveFactor");
|
||||
DecomposeEmissionColor(c, out var emissiveAmount, out var maxEmissiveAmount);
|
||||
material.EmissiveFactor = emissiveAmount.ToNumericsColorRaw();
|
||||
|
||||
if(maxEmissiveAmount > 1)
|
||||
{
|
||||
material.AddExtension(KHR_materials_emissive_strength_Factory.EXTENSION_NAME, new KHR_materials_emissive_strength() { emissiveStrength = maxEmissiveAmount });
|
||||
DeclareExtensionUsage(KHR_materials_emissive_strength_Factory.EXTENSION_NAME, false);
|
||||
}
|
||||
}
|
||||
|
||||
if (materialObj.HasProperty("_EmissionMap") || materialObj.HasProperty("_EmissiveMap") || materialObj.HasProperty("_EmissiveTexture") || materialObj.HasProperty("emissiveTexture"))
|
||||
{
|
||||
var propName = materialObj.HasProperty("emissiveTexture") ? "emissiveTexture" : materialObj.HasProperty("_EmissiveTexture") ? "_EmissiveTexture" : materialObj.HasProperty("_EmissionMap") ? "_EmissionMap" : "_EmissiveMap";
|
||||
var emissionTex = materialObj.GetTexture(propName);
|
||||
|
||||
if (emissionTex)
|
||||
{
|
||||
if(emissionTex is Texture2D)
|
||||
{
|
||||
material.EmissiveTexture = ExportTextureInfo(emissionTex, TextureMapType.Emissive);
|
||||
|
||||
ExportTextureTransform(material.EmissiveTexture, materialObj, propName);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogFormat(LogType.Error, "Can't export a {0} emissive texture in material {1}", emissionTex.GetType(), materialObj.name);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// workaround for glTFast roundtrip: has a _BumpMap but no _NORMALMAP or _BUMPMAP keyword.
|
||||
var is_glTFastShader = materialObj.shader.name.IndexOf("glTF", StringComparison.Ordinal) > -1;
|
||||
if (materialObj.HasProperty("_BumpMap") && (materialObj.IsKeywordEnabled("_NORMALMAP") || materialObj.IsKeywordEnabled("_BUMPMAP") || is_glTFastShader))
|
||||
{
|
||||
var normalTex = materialObj.GetTexture("_BumpMap");
|
||||
|
||||
if (normalTex)
|
||||
{
|
||||
if(normalTex is Texture2D)
|
||||
{
|
||||
material.NormalTexture = ExportNormalTextureInfo(normalTex, TextureMapType.Normal, materialObj);
|
||||
ExportTextureTransform(material.NormalTexture, materialObj, "_BumpMap");
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogFormat(LogType.Error, "Can't export a {0} normal texture in material {1}", normalTex.GetType(), materialObj.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (materialObj.HasProperty("normalTexture") || materialObj.HasProperty("_NormalTexture"))
|
||||
{
|
||||
var propName = materialObj.HasProperty("normalTexture") ? "normalTexture" : "_NormalTexture";
|
||||
var normalTex = materialObj.GetTexture(propName);
|
||||
|
||||
if (normalTex)
|
||||
{
|
||||
if(normalTex is Texture2D)
|
||||
{
|
||||
material.NormalTexture = ExportNormalTextureInfo(normalTex, TextureMapType.Normal, materialObj);
|
||||
ExportTextureTransform(material.NormalTexture, materialObj, propName);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogFormat(LogType.Error, "Can't export a {0} normal texture in material {1}", normalTex.GetType(), materialObj.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (materialObj.HasProperty("_OcclusionMap") || materialObj.HasProperty("occlusionTexture") || materialObj.HasProperty("_OcclusionTexture"))
|
||||
{
|
||||
var propName = materialObj.HasProperty("occlusionTexture") ? "occlusionTexture" : materialObj.HasProperty("_OcclusionTexture") ? "_OcclusionTexture" : "_OcclusionMap";
|
||||
var occTex = materialObj.GetTexture(propName);
|
||||
if (occTex)
|
||||
{
|
||||
if(occTex is Texture2D)
|
||||
{
|
||||
material.OcclusionTexture = ExportOcclusionTextureInfo(occTex, TextureMapType.Occlusion, materialObj);
|
||||
ExportTextureTransform(material.OcclusionTexture, materialObj, propName);
|
||||
material.OcclusionTexture.TexCoord = materialObj.HasProperty("occlusionTextureTexCoord") ?
|
||||
Mathf.RoundToInt(materialObj.GetFloat("occlusionTextureTexCoord")) :
|
||||
materialObj.HasProperty("_OcclusionTextureTexCoord") ?
|
||||
Mathf.RoundToInt(materialObj.GetFloat("_OcclusionTextureTexCoord")) : 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogFormat(LogType.Error, "Can't export a {0} occlusion texture in material {1}", occTex.GetType(), materialObj.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (IsUnlit(materialObj))
|
||||
{
|
||||
ExportUnlit( material, materialObj );
|
||||
}
|
||||
else if (IsPBRMetallicRoughness(materialObj))
|
||||
{
|
||||
material.PbrMetallicRoughness = ExportPBRMetallicRoughness(materialObj);
|
||||
}
|
||||
else if (IsPBRSpecularGlossiness(materialObj))
|
||||
{
|
||||
ExportPBRSpecularGlossiness(material, materialObj);
|
||||
}
|
||||
else if (IsCommonConstant(materialObj))
|
||||
{
|
||||
material.CommonConstant = ExportCommonConstant(materialObj);
|
||||
}
|
||||
else if (materialObj.HasProperty("_BaseMap"))
|
||||
{
|
||||
var mainTex = materialObj.GetTexture("_BaseMap");
|
||||
material.PbrMetallicRoughness = new PbrMetallicRoughness()
|
||||
{
|
||||
BaseColorFactor = (materialObj.HasProperty("_BaseColor")
|
||||
? materialObj.GetColor("_BaseColor")
|
||||
: Color.white).ToNumericsColorLinear(),
|
||||
BaseColorTexture = mainTex ? ExportTextureInfo(mainTex, TextureMapType.BaseColor) : null
|
||||
};
|
||||
}
|
||||
else if (materialObj.HasProperty("_ColorTexture"))
|
||||
{
|
||||
var mainTex = materialObj.GetTexture("_ColorTexture");
|
||||
material.PbrMetallicRoughness = new PbrMetallicRoughness()
|
||||
{
|
||||
BaseColorFactor = (materialObj.HasProperty("_BaseColor")
|
||||
? materialObj.GetColor("_BaseColor")
|
||||
: Color.white).ToNumericsColorLinear(),
|
||||
BaseColorTexture = mainTex ? ExportTextureInfo(mainTex, TextureMapType.BaseColor) : null
|
||||
};
|
||||
}
|
||||
else if (materialObj.HasProperty("_MainTex")) //else export main texture
|
||||
{
|
||||
var mainTex = materialObj.GetTexture("_MainTex");
|
||||
|
||||
if (mainTex != null)
|
||||
{
|
||||
material.PbrMetallicRoughness = new PbrMetallicRoughness() { MetallicFactor = 0, RoughnessFactor = 1.0f };
|
||||
material.PbrMetallicRoughness.BaseColorTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
|
||||
ExportTextureTransform(material.PbrMetallicRoughness.BaseColorTexture, materialObj, "_MainTex");
|
||||
}
|
||||
if (materialObj.HasProperty("_TintColor")) //particles use _TintColor instead of _Color
|
||||
{
|
||||
if (material.PbrMetallicRoughness == null)
|
||||
material.PbrMetallicRoughness = new PbrMetallicRoughness() { MetallicFactor = 0, RoughnessFactor = 1.0f };
|
||||
|
||||
material.PbrMetallicRoughness.BaseColorFactor = materialObj.GetColor("_TintColor").ToNumericsColorLinear();
|
||||
}
|
||||
material.DoubleSided = true;
|
||||
}
|
||||
|
||||
exportMaterialMarker.End();
|
||||
|
||||
return CreateAndAddMaterialId(materialObj, material);
|
||||
}
|
||||
|
||||
private MaterialId CreateAndAddMaterialId(Material materialObj, GLTFMaterial material)
|
||||
{
|
||||
var key = materialObj ? materialObj.GetInstanceID() : 0;
|
||||
if(!_exportedMaterials.ContainsKey(key))
|
||||
_exportedMaterials.Add(key, _root.Materials.Count);
|
||||
|
||||
var id = new MaterialId
|
||||
{
|
||||
Id = _root.Materials.Count,
|
||||
Root = _root
|
||||
};
|
||||
_root.Materials.Add(material);
|
||||
|
||||
// after material export
|
||||
afterMaterialExportMarker.Begin();
|
||||
if (materialObj)
|
||||
{
|
||||
_exportOptions.AfterMaterialExport?.Invoke(this, _root, materialObj, material);
|
||||
AfterMaterialExport?.Invoke(this, _root, materialObj, material);
|
||||
}
|
||||
afterMaterialExportMarker.End();
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
private bool IsPBRMetallicRoughness(Material material)
|
||||
{
|
||||
return (material.HasProperty("_Metallic") || material.HasProperty("_MetallicFactor") || material.HasProperty("metallicFactor")) &&
|
||||
(material.HasProperty("_MetallicGlossMap") || material.HasProperty("_Glossiness") ||
|
||||
material.HasProperty("_Roughness") || material.HasProperty("_RoughnessFactor") || material.HasProperty("roughnessFactor") ||
|
||||
material.HasProperty("_MetallicRoughnessTexture") || material.HasProperty("metallicRoughnessTexture"));
|
||||
}
|
||||
|
||||
private bool IsUnlit(Material material)
|
||||
{
|
||||
return material.shader.name.ToLowerInvariant().Contains("unlit");
|
||||
}
|
||||
|
||||
private bool IsPBRSpecularGlossiness(Material material)
|
||||
{
|
||||
return material.HasProperty("_SpecColor") && material.HasProperty("_SpecGlossMap");
|
||||
}
|
||||
|
||||
private bool IsCommonConstant(Material material)
|
||||
{
|
||||
return material.HasProperty("_AmbientFactor") &&
|
||||
material.HasProperty("_LightMap") &&
|
||||
material.HasProperty("_LightFactor");
|
||||
}
|
||||
|
||||
#if UNITY_2019_1_OR_NEWER
|
||||
private static bool CheckForPropertyInShader(Shader shader, string name, ShaderPropertyType type)
|
||||
{
|
||||
// TODO result can be cached, we might do many similar checks for one export
|
||||
|
||||
var c = shader.GetPropertyCount();
|
||||
var foundProperty = false;
|
||||
for (var i = 0; i < c; i++)
|
||||
{
|
||||
if (shader.GetPropertyName(i) == name && shader.GetPropertyType(i) == type)
|
||||
{
|
||||
foundProperty = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return foundProperty;
|
||||
}
|
||||
#endif
|
||||
|
||||
private void ExportTextureTransform(TextureInfo def, Material mat, string texName)
|
||||
{
|
||||
// early out if texture transform is explicitly disabled
|
||||
if (mat.HasProperty("_TEXTURE_TRANSFORM") && !mat.IsKeywordEnabled("_TEXTURE_TRANSFORM_ON"))
|
||||
return;
|
||||
|
||||
Vector2 offset = mat.GetTextureOffset(texName);
|
||||
Vector2 scale = mat.GetTextureScale(texName);
|
||||
//var rotationMatrix = mat.GetVector(texName + "Rotation");
|
||||
//var rotation = -Mathf.Atan2(offset.y, rotationMatrix.x);
|
||||
var rotProp = texName + "Rotation";
|
||||
var rotation = 0f;
|
||||
#if UNITY_2021_1_OR_NEWER
|
||||
if (mat.HasFloat(rotProp))
|
||||
#else
|
||||
if (mat.HasProperty(rotProp)
|
||||
#if UNITY_2019_1_OR_NEWER
|
||||
&& CheckForPropertyInShader(mat.shader, rotProp, ShaderPropertyType.Float)
|
||||
#endif
|
||||
)
|
||||
#endif
|
||||
rotation = mat.GetFloat(rotProp);
|
||||
|
||||
if (offset == Vector2.zero && scale == Vector2.one && rotation == 0)
|
||||
{
|
||||
var checkForName = texName + "_ST";
|
||||
// Debug.Log("Checking for property: " + checkForName + " : " + mat.HasProperty(checkForName) + " == " + (mat.HasProperty(checkForName) ? mat.GetVector(checkForName) : "null"));
|
||||
var textureHasTilingOffset = mat.HasProperty(checkForName);
|
||||
|
||||
#if UNITY_2019_1_OR_NEWER
|
||||
// turns out we have to check extra hard if that property actually exists
|
||||
// the material ALWAYS says true for mat.HasProperty(someTex_ST) when someTex is defined and doesn't have [NoTextureScale] attribute
|
||||
if (textureHasTilingOffset)
|
||||
{
|
||||
if (!CheckForPropertyInShader(mat.shader, checkForName, ShaderPropertyType.Vector))
|
||||
textureHasTilingOffset = false;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (textureHasTilingOffset)
|
||||
{
|
||||
// ignore, texture has explicit _ST property
|
||||
}
|
||||
else if(mat.HasProperty("_MainTex_ST") || mat.HasProperty("_BaseMap_ST") || mat.HasProperty("_BaseColorMap_ST") || mat.HasProperty("_BaseColorTexture_ST") || mat.HasProperty("baseColorTexture_ST"))
|
||||
{
|
||||
// difficult choice here: some shaders might support texture transform per-texture, others use the main transform.
|
||||
if (mat.HasProperty("baseColorTexture"))
|
||||
{
|
||||
offset = mat.GetTextureOffset("baseColorTexture");
|
||||
scale = mat.GetTextureScale("baseColorTexture");
|
||||
rotation = mat.HasProperty("baseColorTextureRotation") ? mat.GetFloat("baseColorTextureRotation") : 0;
|
||||
}
|
||||
else if (mat.HasProperty("_BaseColorTexture"))
|
||||
{
|
||||
offset = mat.GetTextureOffset("_BaseColorTexture");
|
||||
scale = mat.GetTextureScale("_BaseColorTexture");
|
||||
rotation = mat.HasProperty("_BaseColorTextureRotation") ? mat.GetFloat("_BaseColorTextureRotation") : 0;
|
||||
}
|
||||
else if (mat.HasProperty("_BaseColorMap"))
|
||||
{
|
||||
offset = mat.GetTextureOffset("_BaseColorMap");
|
||||
scale = mat.GetTextureScale("_BaseColorMap");
|
||||
}
|
||||
else if (mat.HasProperty("_BaseMap"))
|
||||
{
|
||||
offset = mat.GetTextureOffset("_BaseMap");
|
||||
scale = mat.GetTextureScale("_BaseMap");
|
||||
}
|
||||
else if(mat.HasProperty("_MainTex"))
|
||||
{
|
||||
offset = mat.mainTextureOffset;
|
||||
scale = mat.mainTextureScale;
|
||||
rotation = 0;
|
||||
#if UNITY_2021_1_OR_NEWER
|
||||
if (mat.HasFloat("_MainTexRotation"))
|
||||
#else
|
||||
if (mat.HasProperty("_MainTexRotation"))
|
||||
#endif
|
||||
rotation = mat.GetFloat("_MainTexRotation");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
offset = Vector2.zero;
|
||||
scale = Vector2.one;
|
||||
}
|
||||
}
|
||||
|
||||
if (_root.ExtensionsUsed == null)
|
||||
{
|
||||
_root.ExtensionsUsed = new List<string>(
|
||||
new[] { ExtTextureTransformExtensionFactory.EXTENSION_NAME }
|
||||
);
|
||||
}
|
||||
else if (!_root.ExtensionsUsed.Contains(ExtTextureTransformExtensionFactory.EXTENSION_NAME))
|
||||
{
|
||||
_root.ExtensionsUsed.Add(ExtTextureTransformExtensionFactory.EXTENSION_NAME);
|
||||
}
|
||||
|
||||
if (RequireExtensions)
|
||||
{
|
||||
if (_root.ExtensionsRequired == null)
|
||||
{
|
||||
_root.ExtensionsRequired = new List<string>(
|
||||
new[] { ExtTextureTransformExtensionFactory.EXTENSION_NAME }
|
||||
);
|
||||
}
|
||||
else if (!_root.ExtensionsRequired.Contains(ExtTextureTransformExtensionFactory.EXTENSION_NAME))
|
||||
{
|
||||
_root.ExtensionsRequired.Add(ExtTextureTransformExtensionFactory.EXTENSION_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
if (def.Extensions == null)
|
||||
def.Extensions = new Dictionary<string, IExtension>();
|
||||
|
||||
def.Extensions[ExtTextureTransformExtensionFactory.EXTENSION_NAME] = new ExtTextureTransformExtension(
|
||||
new GLTF.Math.Vector2(offset.x, 1 - offset.y - scale.y),
|
||||
rotation,
|
||||
new GLTF.Math.Vector2(scale.x, scale.y),
|
||||
0 // TODO: support UV channels
|
||||
);
|
||||
}
|
||||
|
||||
public NormalTextureInfo ExportNormalTextureInfo(
|
||||
Texture texture,
|
||||
string textureSlot,
|
||||
Material material)
|
||||
{
|
||||
var info = new NormalTextureInfo();
|
||||
|
||||
info.Index = ExportTexture(texture, textureSlot);
|
||||
|
||||
if (material.HasProperty("normalScale"))
|
||||
{
|
||||
info.Scale = material.GetFloat("normalScale");
|
||||
}
|
||||
else if (material.HasProperty("_NormalScale"))
|
||||
{
|
||||
info.Scale = material.GetFloat("_NormalScale");
|
||||
}
|
||||
else if (material.HasProperty("_BumpScale"))
|
||||
{
|
||||
info.Scale = material.GetFloat("_BumpScale");
|
||||
}
|
||||
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
private OcclusionTextureInfo ExportOcclusionTextureInfo(
|
||||
Texture texture,
|
||||
string textureSlot,
|
||||
Material material)
|
||||
{
|
||||
var info = new OcclusionTextureInfo();
|
||||
|
||||
info.Index = ExportTexture(texture, textureSlot);
|
||||
|
||||
if (material.HasProperty("occlusionStrength"))
|
||||
{
|
||||
info.Strength = material.GetFloat("occlusionStrength");
|
||||
}
|
||||
else if (material.HasProperty("_OcclusionStrength"))
|
||||
{
|
||||
info.Strength = material.GetFloat("_OcclusionStrength");
|
||||
}
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
public PbrMetallicRoughness ExportPBRMetallicRoughness(Material material)
|
||||
{
|
||||
var pbr = new PbrMetallicRoughness() { MetallicFactor = 0, RoughnessFactor = 1.0f };
|
||||
var isGltfPbrMetallicRoughnessShader = material.shader.name.Equals("GLTF/PbrMetallicRoughness", StringComparison.Ordinal);
|
||||
var isGlTFastShader = material.shader.name.Equals("glTF/PbrMetallicRoughness", StringComparison.Ordinal);
|
||||
|
||||
if (material.HasProperty("baseColorFactor"))
|
||||
{
|
||||
pbr.BaseColorFactor = material.GetColor("baseColorFactor").ToNumericsColorLinear();
|
||||
}
|
||||
else if (material.HasProperty("_BaseColorFactor"))
|
||||
{
|
||||
pbr.BaseColorFactor = material.GetColor("_BaseColorFactor").ToNumericsColorLinear();
|
||||
}
|
||||
else if (material.HasProperty("_BaseColor"))
|
||||
{
|
||||
pbr.BaseColorFactor = material.GetColor("_BaseColor").ToNumericsColorLinear();
|
||||
}
|
||||
else if (material.HasProperty("_Color"))
|
||||
{
|
||||
pbr.BaseColorFactor = material.GetColor("_Color").ToNumericsColorLinear();
|
||||
}
|
||||
|
||||
if (material.HasProperty("_TintColor")) //particles use _TintColor instead of _Color
|
||||
{
|
||||
float white = 1;
|
||||
if (material.HasProperty("_Color"))
|
||||
{
|
||||
var c = material.GetColor("_Color");
|
||||
white = (c.r + c.g + c.b) / 3.0f; //multiply alpha by overall whiteness of TintColor
|
||||
}
|
||||
|
||||
pbr.BaseColorFactor = (material.GetColor("_TintColor") * white).ToNumericsColorLinear() ;
|
||||
}
|
||||
|
||||
if (material.HasProperty("_MainTex") || material.HasProperty("_BaseMap") || material.HasProperty("_BaseColorTexture") || material.HasProperty("baseColorTexture")) //TODO if additive particle, render black into alpha
|
||||
{
|
||||
// TODO use private Material.GetFirstPropertyNameIdByAttribute here, supported from 2020.1+
|
||||
var mainTexPropertyName = material.HasProperty("_BaseMap") ? "_BaseMap" : material.HasProperty("_MainTex") ? "_MainTex" : material.HasProperty("baseColorTexture") ? "baseColorTexture" : "_BaseColorTexture";
|
||||
var mainTex = material.GetTexture(mainTexPropertyName);
|
||||
|
||||
if (mainTex)
|
||||
{
|
||||
pbr.BaseColorTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
|
||||
ExportTextureTransform(pbr.BaseColorTexture, material, mainTexPropertyName);
|
||||
pbr.BaseColorTexture.TexCoord = material.HasProperty("baseColorTextureTexCoord") ?
|
||||
Mathf.RoundToInt(material.GetFloat("baseColorTextureTexCoord")) :
|
||||
material.HasProperty("_BaseColorTextureTexCoord") ?
|
||||
Mathf.RoundToInt(material.GetFloat("_BaseColorTextureTexCoord")) : 0;
|
||||
}
|
||||
}
|
||||
|
||||
var ignoreMetallicFactor = (material.IsKeywordEnabled("_METALLICGLOSSMAP") || material.IsKeywordEnabled("_METALLICSPECGLOSSMAP")) && !isGltfPbrMetallicRoughnessShader && !isGlTFastShader;
|
||||
if (material.HasProperty("metallicFactor") && !ignoreMetallicFactor)
|
||||
{
|
||||
pbr.MetallicFactor = material.GetFloat("metallicFactor");
|
||||
}
|
||||
else if (material.HasProperty("_MetallicFactor") && !ignoreMetallicFactor)
|
||||
{
|
||||
pbr.MetallicFactor = material.GetFloat("_MetallicFactor");
|
||||
}
|
||||
else if (material.HasProperty("_Metallic") && !ignoreMetallicFactor)
|
||||
{
|
||||
pbr.MetallicFactor = material.GetFloat("_Metallic");
|
||||
}
|
||||
|
||||
var needToBakeRoughnessIntoTexture = false;
|
||||
float roughnessMultiplier = 1f;
|
||||
|
||||
if (material.HasProperty("roughnessFactor"))
|
||||
{
|
||||
float roughness = material.GetFloat("roughnessFactor");
|
||||
pbr.RoughnessFactor = roughness;
|
||||
}
|
||||
else if (material.HasProperty("_RoughnessFactor"))
|
||||
{
|
||||
float roughness = material.GetFloat("_RoughnessFactor");
|
||||
pbr.RoughnessFactor = roughness;
|
||||
}
|
||||
else if (material.HasProperty("_Roughness"))
|
||||
{
|
||||
float roughness = material.GetFloat("_Roughness");
|
||||
pbr.RoughnessFactor = roughness;
|
||||
}
|
||||
else if (material.HasProperty("_Glossiness") || material.HasProperty("_Smoothness"))
|
||||
{
|
||||
var smoothnessPropertyName = material.HasProperty("_Smoothness") ? "_Smoothness" : "_Glossiness";
|
||||
var metallicGlossMap = material.HasProperty("_MetallicGlossMap") ? material.GetTexture("_MetallicGlossMap") : null;
|
||||
float smoothness = material.GetFloat(smoothnessPropertyName);
|
||||
|
||||
// legacy workaround: the UnityGLTF shaders misuse "_Glossiness" as roughness but don't have a keyword for it.
|
||||
if (isGltfPbrMetallicRoughnessShader)
|
||||
smoothness = 1 - smoothness;
|
||||
if (metallicGlossMap && material.HasProperty("_GlossMapScale") && material.IsKeywordEnabled("_METALLICGLOSSMAP"))
|
||||
smoothness = material.GetFloat("_GlossMapScale");
|
||||
|
||||
var hasMetallicRoughnessMap =
|
||||
(material.HasProperty("metallicRoughnessTexture") && material.GetTexture("metallicRoughnessTexture")) ||
|
||||
(material.HasProperty("_MetallicRoughnessTexture") && material.GetTexture("_MetallicRoughnessTexture")) ||
|
||||
(material.HasProperty("_MetallicGlossMap") && material.GetTexture("_MetallicGlossMap"));
|
||||
|
||||
if (!hasMetallicRoughnessMap)
|
||||
pbr.RoughnessFactor = 1 - smoothness;
|
||||
else
|
||||
{
|
||||
needToBakeRoughnessIntoTexture = true;
|
||||
roughnessMultiplier = 1 - smoothness;
|
||||
pbr.RoughnessFactor = 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (material.HasProperty("metallicRoughnessTexture"))
|
||||
{
|
||||
var mrTex = material.GetTexture("metallicRoughnessTexture");
|
||||
if (mrTex)
|
||||
{
|
||||
pbr.MetallicRoughnessTexture = ExportTextureInfo(mrTex, TextureMapType.MetallicRoughness);
|
||||
}
|
||||
}
|
||||
else if (material.HasProperty("_MetallicRoughnessTexture"))
|
||||
{
|
||||
var mrTex = material.GetTexture("_MetallicRoughnessTexture");
|
||||
if (mrTex)
|
||||
{
|
||||
pbr.MetallicRoughnessTexture = ExportTextureInfo(mrTex, TextureMapType.MetallicRoughness);
|
||||
}
|
||||
}
|
||||
else if (material.HasProperty("_MetallicGlossMap"))
|
||||
{
|
||||
var mrTex = material.GetTexture("_MetallicGlossMap");
|
||||
|
||||
if (mrTex)
|
||||
{
|
||||
var conversion = GetExportSettingsForSlot((isGltfPbrMetallicRoughnessShader || isGlTFastShader) ? TextureMapType.Linear : TextureMapType.MetallicGloss);
|
||||
if (needToBakeRoughnessIntoTexture)
|
||||
{
|
||||
conversion = new TextureExportSettings(conversion);
|
||||
conversion.smoothnessMultiplier = 1 - roughnessMultiplier;
|
||||
}
|
||||
pbr.MetallicRoughnessTexture = ExportTextureInfo(mrTex, TextureMapType.MetallicRoughness, conversion);
|
||||
// in the Standard shader, _METALLICGLOSSMAP replaces _Metallic and so we need to set the multiplier to 1;
|
||||
// that's not true for the gltf shaders though, so we keep the value there.
|
||||
if (ignoreMetallicFactor)
|
||||
pbr.MetallicFactor = 1.0f;
|
||||
ExportTextureTransform(pbr.MetallicRoughnessTexture, material, "_MetallicGlossMap");
|
||||
}
|
||||
}
|
||||
|
||||
return pbr;
|
||||
}
|
||||
|
||||
public void ExportUnlit(GLTFMaterial def, Material material){
|
||||
|
||||
const string extname = KHR_MaterialsUnlitExtensionFactory.EXTENSION_NAME;
|
||||
DeclareExtensionUsage( extname, true );
|
||||
def.AddExtension( extname, new KHR_MaterialsUnlitExtension());
|
||||
|
||||
var pbr = new PbrMetallicRoughness();
|
||||
|
||||
if (material.HasProperty("baseColorFactor"))
|
||||
{
|
||||
pbr.BaseColorFactor = material.GetColor("baseColorFactor").ToNumericsColorLinear();
|
||||
}
|
||||
else if (material.HasProperty("_BaseColorFactor"))
|
||||
{
|
||||
pbr.BaseColorFactor = material.GetColor("_BaseColorFactor").ToNumericsColorLinear();
|
||||
}
|
||||
else if (material.HasProperty("_BaseColor"))
|
||||
{
|
||||
pbr.BaseColorFactor = material.GetColor("_BaseColor").ToNumericsColorLinear();
|
||||
}
|
||||
else if (material.HasProperty("_Color"))
|
||||
{
|
||||
pbr.BaseColorFactor = material.GetColor("_Color").ToNumericsColorLinear();
|
||||
}
|
||||
|
||||
if (material.HasProperty("baseColorTexture"))
|
||||
{
|
||||
var mainTex = material.GetTexture("baseColorTexture");
|
||||
if (mainTex)
|
||||
{
|
||||
pbr.BaseColorTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
|
||||
ExportTextureTransform(pbr.BaseColorTexture, material, "baseColorTexture");
|
||||
}
|
||||
}
|
||||
else if (material.HasProperty("_BaseColorTexture"))
|
||||
{
|
||||
var mainTex = material.GetTexture("_BaseColorTexture");
|
||||
if (mainTex)
|
||||
{
|
||||
pbr.BaseColorTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
|
||||
ExportTextureTransform(pbr.BaseColorTexture, material, "_BaseColorTexture");
|
||||
}
|
||||
}
|
||||
else if (material.HasProperty("_BaseMap"))
|
||||
{
|
||||
var mainTex = material.GetTexture("_BaseMap");
|
||||
if (mainTex)
|
||||
{
|
||||
pbr.BaseColorTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
|
||||
ExportTextureTransform(pbr.BaseColorTexture, material, "_BaseMap");
|
||||
}
|
||||
}
|
||||
else if (material.HasProperty("_MainTex"))
|
||||
{
|
||||
var mainTex = material.GetTexture("_MainTex");
|
||||
if (mainTex)
|
||||
{
|
||||
pbr.BaseColorTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
|
||||
ExportTextureTransform(pbr.BaseColorTexture, material, "_MainTex");
|
||||
}
|
||||
}
|
||||
|
||||
def.PbrMetallicRoughness = pbr;
|
||||
|
||||
}
|
||||
|
||||
private void ExportPBRSpecularGlossiness(GLTFMaterial material, Material materialObj)
|
||||
{
|
||||
if (_root.ExtensionsUsed == null)
|
||||
{
|
||||
_root.ExtensionsUsed = new List<string>(new[] { "KHR_materials_pbrSpecularGlossiness" });
|
||||
}
|
||||
else if (!_root.ExtensionsUsed.Contains("KHR_materials_pbrSpecularGlossiness"))
|
||||
{
|
||||
_root.ExtensionsUsed.Add("KHR_materials_pbrSpecularGlossiness");
|
||||
}
|
||||
|
||||
if (RequireExtensions)
|
||||
{
|
||||
if (_root.ExtensionsRequired == null)
|
||||
{
|
||||
_root.ExtensionsRequired = new List<string>(new[] { "KHR_materials_pbrSpecularGlossiness" });
|
||||
}
|
||||
else if (!_root.ExtensionsRequired.Contains("KHR_materials_pbrSpecularGlossiness"))
|
||||
{
|
||||
_root.ExtensionsRequired.Add("KHR_materials_pbrSpecularGlossiness");
|
||||
}
|
||||
}
|
||||
|
||||
if (material.Extensions == null)
|
||||
{
|
||||
material.Extensions = new Dictionary<string, IExtension>();
|
||||
}
|
||||
|
||||
GLTF.Math.Color diffuseFactor = KHR_materials_pbrSpecularGlossinessExtension.DIFFUSE_FACTOR_DEFAULT;
|
||||
TextureInfo diffuseTexture = KHR_materials_pbrSpecularGlossinessExtension.DIFFUSE_TEXTURE_DEFAULT;
|
||||
GLTF.Math.Vector3 specularFactor = KHR_materials_pbrSpecularGlossinessExtension.SPEC_FACTOR_DEFAULT;
|
||||
double glossinessFactor = KHR_materials_pbrSpecularGlossinessExtension.GLOSS_FACTOR_DEFAULT;
|
||||
TextureInfo specularGlossinessTexture = KHR_materials_pbrSpecularGlossinessExtension.SPECULAR_GLOSSINESS_TEXTURE_DEFAULT;
|
||||
|
||||
if (materialObj.HasProperty("_BaseColor"))
|
||||
{
|
||||
diffuseFactor = materialObj.GetColor("_BaseColor").ToNumericsColorLinear();
|
||||
}
|
||||
else if (materialObj.HasProperty("_Color"))
|
||||
{
|
||||
diffuseFactor = materialObj.GetColor("_Color").ToNumericsColorLinear();
|
||||
}
|
||||
|
||||
if (materialObj.HasProperty("_BaseMap"))
|
||||
{
|
||||
var mainTex = materialObj.GetTexture("_BaseMap");
|
||||
|
||||
if (mainTex != null)
|
||||
{
|
||||
diffuseTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
|
||||
ExportTextureTransform(diffuseTexture, materialObj, "_BaseMap");
|
||||
}
|
||||
}
|
||||
else if (materialObj.HasProperty("_MainTex"))
|
||||
{
|
||||
var mainTex = materialObj.GetTexture("_MainTex");
|
||||
|
||||
if (mainTex != null)
|
||||
{
|
||||
diffuseTexture = ExportTextureInfo(mainTex, TextureMapType.BaseColor);
|
||||
ExportTextureTransform(diffuseTexture, materialObj, "_MainTex");
|
||||
}
|
||||
}
|
||||
|
||||
if (materialObj.HasProperty("_SpecColor"))
|
||||
{
|
||||
var specGlossMap = materialObj.GetTexture("_SpecGlossMap");
|
||||
if (specGlossMap == null)
|
||||
{
|
||||
var specColor = materialObj.GetColor("_SpecColor").ToNumericsColorLinear();
|
||||
specularFactor = new GLTF.Math.Vector3(specColor.R, specColor.G, specColor.B);
|
||||
}
|
||||
}
|
||||
|
||||
if (materialObj.HasProperty("_Glossiness"))
|
||||
{
|
||||
var specGlossMap = materialObj.GetTexture("_SpecGlossMap");
|
||||
if (specGlossMap == null)
|
||||
{
|
||||
glossinessFactor = materialObj.GetFloat("_Glossiness");
|
||||
}
|
||||
}
|
||||
|
||||
if (materialObj.HasProperty("_SpecGlossMap"))
|
||||
{
|
||||
var mgTex = materialObj.GetTexture("_SpecGlossMap");
|
||||
|
||||
if (mgTex)
|
||||
{
|
||||
specularGlossinessTexture = ExportTextureInfo(mgTex, TextureMapType.SpecGloss);
|
||||
ExportTextureTransform(specularGlossinessTexture, materialObj, "_SpecGlossMap");
|
||||
}
|
||||
}
|
||||
|
||||
material.Extensions[KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME] = new KHR_materials_pbrSpecularGlossinessExtension(
|
||||
diffuseFactor,
|
||||
diffuseTexture,
|
||||
specularFactor,
|
||||
glossinessFactor,
|
||||
specularGlossinessTexture
|
||||
);
|
||||
}
|
||||
|
||||
private MaterialCommonConstant ExportCommonConstant(Material materialObj)
|
||||
{
|
||||
if (_root.ExtensionsUsed == null)
|
||||
{
|
||||
_root.ExtensionsUsed = new List<string>(new[] { "KHR_materials_common" });
|
||||
}
|
||||
else if (!_root.ExtensionsUsed.Contains("KHR_materials_common"))
|
||||
{
|
||||
_root.ExtensionsUsed.Add("KHR_materials_common");
|
||||
}
|
||||
|
||||
if (RequireExtensions)
|
||||
{
|
||||
if (_root.ExtensionsRequired == null)
|
||||
{
|
||||
_root.ExtensionsRequired = new List<string>(new[] { "KHR_materials_common" });
|
||||
}
|
||||
else if (!_root.ExtensionsRequired.Contains("KHR_materials_common"))
|
||||
{
|
||||
_root.ExtensionsRequired.Add("KHR_materials_common");
|
||||
}
|
||||
}
|
||||
|
||||
var constant = new MaterialCommonConstant();
|
||||
|
||||
if (materialObj.HasProperty("_AmbientFactor"))
|
||||
{
|
||||
constant.AmbientFactor = materialObj.GetColor("_AmbientFactor").ToNumericsColorRaw();
|
||||
}
|
||||
|
||||
if (materialObj.HasProperty("_LightMap"))
|
||||
{
|
||||
var lmTex = materialObj.GetTexture("_LightMap");
|
||||
|
||||
if (lmTex)
|
||||
{
|
||||
constant.LightmapTexture = ExportTextureInfo(lmTex, TextureMapType.Linear);
|
||||
ExportTextureTransform(constant.LightmapTexture, materialObj, "_LightMap");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (materialObj.HasProperty("_LightFactor"))
|
||||
{
|
||||
constant.LightmapFactor = materialObj.GetColor("_LightFactor").ToNumericsColorRaw();
|
||||
}
|
||||
|
||||
return constant;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e09c9ec7a50e4331bd773f4c54f1b9ab
|
||||
timeCreated: 1657010581
|
||||
@@ -0,0 +1,526 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using GLTF.Schema;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
using UnityGLTF.Extensions;
|
||||
|
||||
#if UNITY_EDITOR // required for in-editor access to non-readable meshes
|
||||
using UnityEditor;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public partial class GLTFSceneExporter
|
||||
{
|
||||
private struct MeshAccessors
|
||||
{
|
||||
public AccessorId aPosition, aNormal, aTangent, aTexcoord0, aTexcoord1, aColor0;
|
||||
public Dictionary<int, MeshPrimitive> subMeshPrimitives;
|
||||
}
|
||||
|
||||
private struct BlendShapeAccessors
|
||||
{
|
||||
public List<Dictionary<string, AccessorId>> targets;
|
||||
public List<Double> weights;
|
||||
public List<string> targetNames;
|
||||
}
|
||||
|
||||
private readonly Dictionary<Mesh, MeshAccessors> _meshToPrims = new Dictionary<Mesh, MeshAccessors>();
|
||||
private readonly Dictionary<Mesh, BlendShapeAccessors> _meshToBlendShapeAccessors = new Dictionary<Mesh, BlendShapeAccessors>();
|
||||
|
||||
public void RegisterPrimitivesWithNode(Node node, List<UniquePrimitive> uniquePrimitives)
|
||||
{
|
||||
// associate unity meshes with gltf mesh id
|
||||
foreach (var primKey in uniquePrimitives)
|
||||
{
|
||||
_primOwner[primKey] = node.Mesh;
|
||||
}
|
||||
}
|
||||
|
||||
private static List<UniquePrimitive> GetUniquePrimitivesFromGameObjects(IEnumerable<GameObject> primitives)
|
||||
{
|
||||
var primKeys = new List<UniquePrimitive>();
|
||||
|
||||
foreach (var prim in primitives)
|
||||
{
|
||||
Mesh meshObj = null;
|
||||
SkinnedMeshRenderer smr = null;
|
||||
var filter = prim.GetComponent<MeshFilter>();
|
||||
if (filter)
|
||||
{
|
||||
meshObj = filter.sharedMesh;
|
||||
}
|
||||
else
|
||||
{
|
||||
smr = prim.GetComponent<SkinnedMeshRenderer>();
|
||||
if (smr)
|
||||
{
|
||||
meshObj = smr.sharedMesh;
|
||||
}
|
||||
}
|
||||
|
||||
if (!meshObj)
|
||||
{
|
||||
Debug.LogWarning($"MeshFilter.sharedMesh on GameObject:{prim.name} is missing, skipping", prim);
|
||||
exportPrimitiveMarker.End();
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
#if UNITY_EDITOR
|
||||
if (!MeshIsReadable(meshObj) && EditorUtility.IsPersistent(meshObj))
|
||||
{
|
||||
#if UNITY_2019_3_OR_NEWER
|
||||
var assetPath = AssetDatabase.GetAssetPath(meshObj);
|
||||
if (assetPath?.Length > 30) assetPath = "..." + assetPath.Substring(assetPath.Length - 30);
|
||||
var otherOption = Application.isPlaying ? "No, skip mesh" : "Cancel export";
|
||||
if(EditorUtility.DisplayDialog("Exporting mesh but mesh is not readable",
|
||||
$"The mesh {meshObj.name} is not readable. Do you want to change its import settings and make it readable now?\n\n" + assetPath,
|
||||
"Make it readable", otherOption,
|
||||
DialogOptOutDecisionType.ForThisSession, MakeMeshReadableDialogueDecisionKey))
|
||||
#endif
|
||||
{
|
||||
var path = AssetDatabase.GetAssetPath(meshObj);
|
||||
var importer = AssetImporter.GetAtPath(path) as ModelImporter;
|
||||
if (importer)
|
||||
{
|
||||
importer.isReadable = true;
|
||||
importer.SaveAndReimport();
|
||||
}
|
||||
}
|
||||
#if UNITY_2019_3_OR_NEWER
|
||||
else
|
||||
{
|
||||
if (Application.isPlaying)
|
||||
{
|
||||
Debug.LogWarning(null, $"The mesh {meshObj.name} is not readable. Skipping", meshObj);
|
||||
exportPrimitiveMarker.End();
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError(null, $"The mesh {meshObj.name} is not readable and you decided to cancel the export. Canceling", meshObj);
|
||||
exportPrimitiveMarker.End();
|
||||
throw new OperationCanceledException($"Canceled export because a mesh ({meshObj}) is not readable.");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
if (Application.isPlaying && !MeshIsReadable(meshObj))
|
||||
{
|
||||
Debug.LogWarning($"The mesh {meshObj.name} is not readable. Skipping", null);
|
||||
exportPrimitiveMarker.End();
|
||||
return null;
|
||||
}
|
||||
|
||||
var renderer = prim.GetComponent<MeshRenderer>();
|
||||
if (!renderer) smr = prim.GetComponent<SkinnedMeshRenderer>();
|
||||
|
||||
if(!renderer && !smr)
|
||||
{
|
||||
Debug.LogWarning("GameObject does have neither renderer nor SkinnedMeshRenderer! " + prim.name, prim);
|
||||
exportPrimitiveMarker.End();
|
||||
return null;
|
||||
}
|
||||
|
||||
var materialsObj = renderer ? renderer.sharedMaterials : smr.sharedMaterials;
|
||||
|
||||
var primKey = new UniquePrimitive();
|
||||
primKey.Mesh = meshObj;
|
||||
primKey.Materials = materialsObj;
|
||||
primKey.SkinnedMeshRenderer = smr;
|
||||
|
||||
primKeys.Add(primKey);
|
||||
}
|
||||
|
||||
return primKeys;
|
||||
}
|
||||
|
||||
public NodeId ExportNode(GameObject gameObject) => ExportNode(gameObject.transform);
|
||||
|
||||
/// <summary>
|
||||
/// Convenience wrapper around ExportMesh(string, List<UniquePrimitive>)
|
||||
/// </summary>
|
||||
public MeshId ExportMesh(Mesh mesh)
|
||||
{
|
||||
var uniquePrimitives = new List<UniquePrimitive>
|
||||
{
|
||||
new UniquePrimitive()
|
||||
{
|
||||
Mesh = mesh,
|
||||
SkinnedMeshRenderer = null,
|
||||
Materials = new [] { DefaultMaterial },
|
||||
}
|
||||
};
|
||||
return ExportMesh(mesh.name, uniquePrimitives);
|
||||
}
|
||||
|
||||
public MeshId ExportMesh(string name, List<UniquePrimitive> uniquePrimitives)
|
||||
{
|
||||
exportMeshMarker.Begin();
|
||||
|
||||
// check if this set of primitives is already a mesh
|
||||
MeshId existingMeshId = null;
|
||||
|
||||
foreach (var prim in uniquePrimitives)
|
||||
{
|
||||
MeshId tempMeshId;
|
||||
if (_primOwner.TryGetValue(prim, out tempMeshId) && (existingMeshId == null || tempMeshId == existingMeshId))
|
||||
{
|
||||
existingMeshId = tempMeshId;
|
||||
}
|
||||
else
|
||||
{
|
||||
existingMeshId = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// if so, return that mesh id
|
||||
if (existingMeshId != null)
|
||||
{
|
||||
exportMeshMarker.End();
|
||||
return existingMeshId;
|
||||
}
|
||||
|
||||
// if not, create new mesh and return its id
|
||||
var mesh = new GLTFMesh();
|
||||
|
||||
if (settings.ExportNames)
|
||||
{
|
||||
mesh.Name = name;
|
||||
}
|
||||
|
||||
mesh.Primitives = new List<MeshPrimitive>(uniquePrimitives.Count);
|
||||
foreach (var primKey in uniquePrimitives)
|
||||
{
|
||||
MeshPrimitive[] meshPrimitives = ExportPrimitive(primKey, mesh);
|
||||
if (meshPrimitives != null)
|
||||
{
|
||||
mesh.Primitives.AddRange(meshPrimitives);
|
||||
}
|
||||
}
|
||||
|
||||
var id = new MeshId
|
||||
{
|
||||
Id = _root.Meshes.Count,
|
||||
Root = _root
|
||||
};
|
||||
|
||||
exportMeshMarker.End();
|
||||
|
||||
if (mesh.Primitives.Count > 0)
|
||||
{
|
||||
_root.Meshes.Add(mesh);
|
||||
return id;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// a mesh *might* decode to multiple prims if there are submeshes
|
||||
private MeshPrimitive[] ExportPrimitive(UniquePrimitive primKey, GLTFMesh mesh)
|
||||
{
|
||||
exportPrimitiveMarker.Begin();
|
||||
|
||||
Mesh meshObj = primKey.Mesh;
|
||||
Material[] materialsObj = primKey.Materials;
|
||||
|
||||
var prims = new MeshPrimitive[meshObj.subMeshCount];
|
||||
List<MeshPrimitive> nonEmptyPrims = null;
|
||||
var vertices = meshObj.vertices;
|
||||
if (vertices.Length < 1)
|
||||
{
|
||||
Debug.LogWarning(null, "MeshFilter does not contain any vertices or they can't be accessed, won't export: " + meshObj.name, meshObj);
|
||||
exportPrimitiveMarker.End();
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!_meshToPrims.ContainsKey(meshObj))
|
||||
{
|
||||
AccessorId aPosition = null, aNormal = null, aTangent = null, aTexcoord0 = null, aTexcoord1 = null, aColor0 = null;
|
||||
|
||||
aPosition = ExportAccessor(SchemaExtensions.ConvertVector3CoordinateSpaceAndCopy(meshObj.vertices, SchemaExtensions.CoordinateSpaceConversionScale));
|
||||
|
||||
if (meshObj.normals.Length != 0)
|
||||
aNormal = ExportAccessor(SchemaExtensions.ConvertVector3CoordinateSpaceAndCopy(meshObj.normals, SchemaExtensions.CoordinateSpaceConversionScale));
|
||||
|
||||
if (meshObj.tangents.Length != 0)
|
||||
aTangent = ExportAccessor(SchemaExtensions.ConvertVector4CoordinateSpaceAndCopy(meshObj.tangents, SchemaExtensions.TangentSpaceConversionScale));
|
||||
|
||||
if (meshObj.uv.Length != 0)
|
||||
aTexcoord0 = ExportAccessor(SchemaExtensions.FlipTexCoordArrayVAndCopy(meshObj.uv));
|
||||
|
||||
if (meshObj.uv2.Length != 0)
|
||||
aTexcoord1 = ExportAccessor(SchemaExtensions.FlipTexCoordArrayVAndCopy(meshObj.uv2));
|
||||
|
||||
if (settings.ExportVertexColors && meshObj.colors.Length != 0)
|
||||
aColor0 = ExportAccessor(QualitySettings.activeColorSpace == ColorSpace.Linear ? meshObj.colors : meshObj.colors.ToLinear(), true);
|
||||
|
||||
aPosition.Value.BufferView.Value.Target = BufferViewTarget.ArrayBuffer;
|
||||
if (aNormal != null) aNormal.Value.BufferView.Value.Target = BufferViewTarget.ArrayBuffer;
|
||||
if (aTangent != null) aTangent.Value.BufferView.Value.Target = BufferViewTarget.ArrayBuffer;
|
||||
if (aTexcoord0 != null) aTexcoord0.Value.BufferView.Value.Target = BufferViewTarget.ArrayBuffer;
|
||||
if (aTexcoord1 != null) aTexcoord1.Value.BufferView.Value.Target = BufferViewTarget.ArrayBuffer;
|
||||
if (aColor0 != null) aColor0.Value.BufferView.Value.Target = BufferViewTarget.ArrayBuffer;
|
||||
|
||||
_meshToPrims.Add(meshObj, new MeshAccessors()
|
||||
{
|
||||
aPosition = aPosition,
|
||||
aNormal = aNormal,
|
||||
aTangent = aTangent,
|
||||
aTexcoord0 = aTexcoord0,
|
||||
aTexcoord1 = aTexcoord1,
|
||||
aColor0 = aColor0,
|
||||
subMeshPrimitives = new Dictionary<int, MeshPrimitive>()
|
||||
});
|
||||
}
|
||||
|
||||
var accessors = _meshToPrims[meshObj];
|
||||
|
||||
// walk submeshes and export the ones with non-null meshes
|
||||
for (int submesh = 0; submesh < meshObj.subMeshCount; submesh++)
|
||||
{
|
||||
var mat = materialsObj[submesh % materialsObj.Length];
|
||||
if (!mat) continue;
|
||||
|
||||
if (!accessors.subMeshPrimitives.ContainsKey(submesh))
|
||||
{
|
||||
var primitive = new MeshPrimitive();
|
||||
|
||||
var topology = meshObj.GetTopology(submesh);
|
||||
var indices = meshObj.GetIndices(submesh);
|
||||
if (topology == MeshTopology.Triangles) SchemaExtensions.FlipTriangleFaces(indices);
|
||||
|
||||
primitive.Mode = GetDrawMode(topology);
|
||||
primitive.Indices = ExportAccessor(indices, true);
|
||||
primitive.Indices.Value.BufferView.Value.Target = BufferViewTarget.ElementArrayBuffer;
|
||||
|
||||
primitive.Attributes = new Dictionary<string, AccessorId>();
|
||||
primitive.Attributes.Add(SemanticProperties.POSITION, accessors.aPosition);
|
||||
|
||||
if (accessors.aNormal != null)
|
||||
primitive.Attributes.Add(SemanticProperties.NORMAL, accessors.aNormal);
|
||||
if (accessors.aTangent != null)
|
||||
primitive.Attributes.Add(SemanticProperties.TANGENT, accessors.aTangent);
|
||||
if (accessors.aTexcoord0 != null)
|
||||
primitive.Attributes.Add(SemanticProperties.TEXCOORD_0, accessors.aTexcoord0);
|
||||
if (accessors.aTexcoord1 != null)
|
||||
primitive.Attributes.Add(SemanticProperties.TEXCOORD_1, accessors.aTexcoord1);
|
||||
if (accessors.aColor0 != null)
|
||||
primitive.Attributes.Add(SemanticProperties.COLOR_0, accessors.aColor0);
|
||||
|
||||
primitive.Material = null;
|
||||
|
||||
ExportBlendShapes(primKey.SkinnedMeshRenderer, meshObj, submesh, primitive, mesh);
|
||||
|
||||
accessors.subMeshPrimitives.Add(submesh, primitive);
|
||||
}
|
||||
|
||||
var submeshPrimitive = accessors.subMeshPrimitives[submesh];
|
||||
prims[submesh] = new MeshPrimitive(submeshPrimitive, _root)
|
||||
{
|
||||
Material = ExportMaterial(mat),
|
||||
};
|
||||
accessors.subMeshPrimitives[submesh] = prims[submesh];
|
||||
}
|
||||
|
||||
nonEmptyPrims = new List<MeshPrimitive>(prims.Length);
|
||||
for (var i = 0; i < prims.Length; i++)
|
||||
{
|
||||
var prim = prims[i];
|
||||
// remove any prims that have empty triangles
|
||||
if (EmptyPrimitive(prim)) continue;
|
||||
// invoke pre export event
|
||||
_exportOptions.AfterPrimitiveExport?.Invoke(this, meshObj, prim, i);
|
||||
nonEmptyPrims.Add(prim);
|
||||
}
|
||||
prims = nonEmptyPrims.ToArray();
|
||||
|
||||
exportPrimitiveMarker.End();
|
||||
|
||||
return prims;
|
||||
}
|
||||
|
||||
// Blend Shapes / Morph Targets
|
||||
// Adopted from Gary Hsu (bghgary)
|
||||
// https://github.com/bghgary/glTF-Tools-for-Unity/blob/master/UnityProject/Assets/Gltf/Editor/Exporter.cs
|
||||
private void ExportBlendShapes(SkinnedMeshRenderer smr, Mesh meshObj, int submeshIndex, MeshPrimitive primitive, GLTFMesh mesh)
|
||||
{
|
||||
if (settings.BlendShapeExportProperties == GLTFSettings.BlendShapeExportPropertyFlags.None)
|
||||
return;
|
||||
|
||||
if (_meshToBlendShapeAccessors.TryGetValue(meshObj, out var data))
|
||||
{
|
||||
mesh.Weights = data.weights;
|
||||
primitive.Targets = data.targets;
|
||||
primitive.TargetNames = data.targetNames;
|
||||
return;
|
||||
}
|
||||
|
||||
if (smr != null && meshObj.blendShapeCount > 0)
|
||||
{
|
||||
List<Dictionary<string, AccessorId>> targets = new List<Dictionary<string, AccessorId>>(meshObj.blendShapeCount);
|
||||
List<Double> weights = new List<double>(meshObj.blendShapeCount);
|
||||
List<string> targetNames = new List<string>(meshObj.blendShapeCount);
|
||||
|
||||
#if UNITY_2019_3_OR_NEWER
|
||||
var meshHasNormals = meshObj.HasVertexAttribute(VertexAttribute.Normal);
|
||||
var meshHasTangents = meshObj.HasVertexAttribute(VertexAttribute.Tangent);
|
||||
#else
|
||||
var meshHasNormals = meshObj.normals.Length > 0;
|
||||
var meshHasTangents = meshObj.tangents.Length > 0;
|
||||
#endif
|
||||
|
||||
for (int blendShapeIndex = 0; blendShapeIndex < meshObj.blendShapeCount; blendShapeIndex++)
|
||||
{
|
||||
exportBlendShapeMarker.Begin();
|
||||
|
||||
targetNames.Add(meshObj.GetBlendShapeName(blendShapeIndex));
|
||||
// As described above, a blend shape can have multiple frames. Given that glTF only supports a single frame
|
||||
// per blend shape, we'll always use the final frame (the one that would be for when 100% weight is applied).
|
||||
int frameIndex = meshObj.GetBlendShapeFrameCount(blendShapeIndex) - 1;
|
||||
|
||||
var deltaVertices = new Vector3[meshObj.vertexCount];
|
||||
var deltaNormals = new Vector3[meshObj.vertexCount];
|
||||
var deltaTangents = new Vector3[meshObj.vertexCount];
|
||||
meshObj.GetBlendShapeFrameVertices(blendShapeIndex, frameIndex, deltaVertices, deltaNormals, deltaTangents);
|
||||
|
||||
var exportTargets = new Dictionary<string, AccessorId>();
|
||||
|
||||
if (!settings.BlendShapeExportSparseAccessors)
|
||||
{
|
||||
var positionAccessor = ExportAccessor(SchemaExtensions.ConvertVector3CoordinateSpaceAndCopy(deltaVertices, SchemaExtensions.CoordinateSpaceConversionScale));
|
||||
positionAccessor.Value.BufferView.Value.Target = BufferViewTarget.ArrayBuffer;
|
||||
exportTargets.Add(SemanticProperties.POSITION, positionAccessor);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Debug.Log("Delta Vertices:\n"+string.Join("\n ", deltaVertices));
|
||||
// Debug.Log("Vertices:\n"+string.Join("\n ", meshObj.vertices));
|
||||
// Experimental: sparse accessor.
|
||||
// - get the accessor we want to base this upon
|
||||
// - this is how position is originally exported:
|
||||
// ExportAccessor(SchemaExtensions.ConvertVector3CoordinateSpaceAndCopy(meshObj.vertices, SchemaExtensions.CoordinateSpaceConversionScale));
|
||||
var baseAccessor = _meshToPrims[meshObj].aPosition;
|
||||
var exportedAccessor = ExportSparseAccessor(null, null, SchemaExtensions.ConvertVector3CoordinateSpaceAndCopy(deltaVertices, SchemaExtensions.CoordinateSpaceConversionScale));
|
||||
if (exportedAccessor != null)
|
||||
{
|
||||
exportTargets.Add(SemanticProperties.POSITION, exportedAccessor);
|
||||
}
|
||||
}
|
||||
|
||||
if (meshHasNormals && settings.BlendShapeExportProperties.HasFlag(GLTFSettings.BlendShapeExportPropertyFlags.Normal))
|
||||
{
|
||||
if (!settings.BlendShapeExportSparseAccessors)
|
||||
{
|
||||
var accessor = ExportAccessor(SchemaExtensions.ConvertVector3CoordinateSpaceAndCopy(deltaNormals, SchemaExtensions.CoordinateSpaceConversionScale));
|
||||
accessor.Value.BufferView.Value.Target = BufferViewTarget.ArrayBuffer;
|
||||
exportTargets.Add(SemanticProperties.NORMAL, accessor);
|
||||
}
|
||||
else
|
||||
{
|
||||
var baseAccessor = _meshToPrims[meshObj].aNormal;
|
||||
exportTargets.Add(SemanticProperties.NORMAL, ExportSparseAccessor(null, null, SchemaExtensions.ConvertVector3CoordinateSpaceAndCopy(deltaVertices, SchemaExtensions.CoordinateSpaceConversionScale)));
|
||||
}
|
||||
}
|
||||
if (meshHasTangents && settings.BlendShapeExportProperties.HasFlag(GLTFSettings.BlendShapeExportPropertyFlags.Tangent))
|
||||
{
|
||||
if (!settings.BlendShapeExportSparseAccessors)
|
||||
{
|
||||
var accessor = ExportAccessor(SchemaExtensions.ConvertVector3CoordinateSpaceAndCopy(deltaTangents, SchemaExtensions.CoordinateSpaceConversionScale));
|
||||
accessor.Value.BufferView.Value.Target = BufferViewTarget.ArrayBuffer;
|
||||
exportTargets.Add(SemanticProperties.TANGENT, accessor);
|
||||
}
|
||||
else
|
||||
{
|
||||
// var baseAccessor = _meshToPrims[meshObj].aTangent;
|
||||
// exportTargets.Add(SemanticProperties.TANGENT, ExportSparseAccessor(baseAccessor, SchemaExtensions.ConvertVector4CoordinateSpaceAndCopy(meshObj.tangents, SchemaExtensions.TangentSpaceConversionScale), SchemaExtensions.ConvertVector4CoordinateSpaceAndCopy(deltaVertices, SchemaExtensions.TangentSpaceConversionScale)));
|
||||
exportTargets.Add(SemanticProperties.TANGENT, ExportAccessor(SchemaExtensions.ConvertVector3CoordinateSpaceAndCopy(deltaTangents, SchemaExtensions.CoordinateSpaceConversionScale)));
|
||||
// Debug.LogWarning("Blend Shape Tangents for " + meshObj + " won't be exported with sparse accessors – sparse accessor for tangents isn't supported right now.");
|
||||
}
|
||||
}
|
||||
targets.Add(exportTargets);
|
||||
|
||||
// We need to get the weight from the SkinnedMeshRenderer because this represents the currently
|
||||
// defined weight by the user to apply to this blend shape. If we instead got the value from
|
||||
// the unityMesh, it would be a _per frame_ weight, and for a single-frame blend shape, that would
|
||||
// always be 100. A blend shape might have more than one frame if a user wanted to more tightly
|
||||
// control how a blend shape will be animated during weight changes (e.g. maybe they want changes
|
||||
// between 0-50% to be really minor, but between 50-100 to be extreme, hence they'd have two frames
|
||||
// where the first frame would have a weight of 50 (meaning any weight between 0-50 should be relative
|
||||
// to the values in this frame) and then any weight between 50-100 would be relevant to the weights in
|
||||
// the second frame. See Post 20 for more info:
|
||||
// https://forum.unity3d.com/threads/is-there-some-method-to-add-blendshape-in-editor.298002/#post-2015679
|
||||
if(exportTargets.Any())
|
||||
weights.Add(smr.GetBlendShapeWeight(blendShapeIndex) / 100);
|
||||
|
||||
exportBlendShapeMarker.End();
|
||||
}
|
||||
|
||||
if(weights.Any() && targets.Any())
|
||||
{
|
||||
mesh.Weights = weights;
|
||||
primitive.Targets = targets;
|
||||
primitive.TargetNames = targetNames;
|
||||
}
|
||||
else
|
||||
{
|
||||
mesh.Weights = null;
|
||||
primitive.Targets = null;
|
||||
primitive.TargetNames = null;
|
||||
}
|
||||
|
||||
// cache the exported data; we can re-use it between all submeshes of a mesh.
|
||||
_meshToBlendShapeAccessors.Add(meshObj, new BlendShapeAccessors()
|
||||
{
|
||||
targets = targets,
|
||||
weights = weights,
|
||||
targetNames = targetNames
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static bool EmptyPrimitive(MeshPrimitive prim)
|
||||
{
|
||||
if (prim == null || prim.Attributes == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static DrawMode GetDrawMode(MeshTopology topology)
|
||||
{
|
||||
switch (topology)
|
||||
{
|
||||
case MeshTopology.Points: return DrawMode.Points;
|
||||
case MeshTopology.Lines: return DrawMode.Lines;
|
||||
case MeshTopology.LineStrip: return DrawMode.LineStrip;
|
||||
case MeshTopology.Triangles: return DrawMode.Triangles;
|
||||
}
|
||||
|
||||
throw new Exception("glTF does not support Unity mesh topology: " + topology);
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
private const string MakeMeshReadableDialogueDecisionKey = nameof(MakeMeshReadableDialogueDecisionKey);
|
||||
private static PropertyInfo canAccessProperty =
|
||||
typeof(Mesh).GetProperty("canAccess", BindingFlags.Instance | BindingFlags.Default | BindingFlags.NonPublic);
|
||||
#endif
|
||||
|
||||
private static bool MeshIsReadable(Mesh mesh)
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
return mesh.isReadable || (bool) (canAccessProperty?.GetMethod?.Invoke(mesh, null) ?? true);
|
||||
#else
|
||||
return mesh.isReadable;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6bd3287ee078412b83c46ff0e7af9c6b
|
||||
timeCreated: 1657013770
|
||||
@@ -0,0 +1,180 @@
|
||||
using System.Collections.Generic;
|
||||
using GLTF.Schema;
|
||||
using UnityEngine;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public partial class GLTFSceneExporter
|
||||
{
|
||||
private List<Transform> _skinnedNodes;
|
||||
private Dictionary<SkinnedMeshRenderer, UnityEngine.Mesh> _bakedMeshes;
|
||||
|
||||
private void ExportSkinFromNode(Transform transform)
|
||||
{
|
||||
exportSkinFromNodeMarker.Begin();
|
||||
|
||||
var go = transform.gameObject;
|
||||
var skin = transform.GetComponent<SkinnedMeshRenderer>();
|
||||
var mesh = GetMeshFromGameObject(go);
|
||||
UniquePrimitive key = new UniquePrimitive();
|
||||
key.Mesh = mesh;
|
||||
key.SkinnedMeshRenderer = skin;
|
||||
key.Materials = GetMaterialsFromGameObject(go);
|
||||
MeshId val;
|
||||
if (!_primOwner.TryGetValue(key, out val))
|
||||
{
|
||||
Debug.Log("No mesh found for skin on " + transform, transform);
|
||||
exportSkinFromNodeMarker.End();
|
||||
return;
|
||||
}
|
||||
GLTF.Schema.Skin gltfSkin = new Skin();
|
||||
|
||||
// early out of this SkinnedMeshRenderer has no bones assigned (could be BlendShapes-only)
|
||||
if (skin.bones == null || skin.bones.Length == 0)
|
||||
{
|
||||
exportSkinFromNodeMarker.End();
|
||||
return;
|
||||
}
|
||||
|
||||
bool allBoneTransformNodesHaveBeenExported = true;
|
||||
for (int i = 0; i < skin.bones.Length; ++i)
|
||||
{
|
||||
if (!skin.bones[i])
|
||||
{
|
||||
Debug.LogWarning("Skin has null bone at index " + i + ": " + skin, skin);
|
||||
continue;
|
||||
}
|
||||
var nodeId = skin.bones[i].GetInstanceID();
|
||||
if (!_exportedTransforms.ContainsKey(nodeId))
|
||||
{
|
||||
allBoneTransformNodesHaveBeenExported = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!allBoneTransformNodesHaveBeenExported)
|
||||
{
|
||||
Debug.LogWarning("Not all bones for SkinnedMeshRenderer " + transform + " were exported. Skin information will be skipped. Make sure the bones are active and enabled if you want to export them.", transform);
|
||||
exportSkinFromNodeMarker.End();
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < skin.bones.Length; ++i)
|
||||
{
|
||||
if (!skin.bones[i])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var nodeId = skin.bones[i].GetInstanceID();
|
||||
|
||||
gltfSkin.Joints.Add(
|
||||
new NodeId
|
||||
{
|
||||
Id = _exportedTransforms[nodeId],
|
||||
Root = _root
|
||||
});
|
||||
}
|
||||
|
||||
gltfSkin.InverseBindMatrices = ExportAccessor(mesh.bindposes);
|
||||
|
||||
Vector4[] bones = boneWeightToBoneVec4(mesh.boneWeights);
|
||||
Vector4[] weights = boneWeightToWeightVec4(mesh.boneWeights);
|
||||
|
||||
if(val != null)
|
||||
{
|
||||
GLTF.Schema.GLTFMesh gltfMesh = _root.Meshes[val.Id];
|
||||
if(gltfMesh != null)
|
||||
{
|
||||
foreach (MeshPrimitive prim in gltfMesh.Primitives)
|
||||
{
|
||||
if (!prim.Attributes.ContainsKey("JOINTS_0"))
|
||||
{
|
||||
var jointsAccessor = ExportAccessorUint(bones);
|
||||
jointsAccessor.Value.BufferView.Value.Target = BufferViewTarget.ArrayBuffer;
|
||||
prim.Attributes.Add("JOINTS_0", jointsAccessor);
|
||||
}
|
||||
|
||||
if (!prim.Attributes.ContainsKey("WEIGHTS_0"))
|
||||
{
|
||||
var weightsAccessor = ExportAccessor(weights);
|
||||
weightsAccessor.Value.BufferView.Value.Target = BufferViewTarget.ArrayBuffer;
|
||||
prim.Attributes.Add("WEIGHTS_0", weightsAccessor);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_root.Nodes[_exportedTransforms[transform.GetInstanceID()]].Skin = new SkinId() { Id = _root.Skins.Count, Root = _root };
|
||||
_root.Skins.Add(gltfSkin);
|
||||
|
||||
exportSkinFromNodeMarker.End();
|
||||
}
|
||||
|
||||
private UnityEngine.Mesh GetMeshFromGameObject(GameObject gameObject)
|
||||
{
|
||||
if (gameObject.GetComponent<MeshFilter>())
|
||||
{
|
||||
return gameObject.GetComponent<MeshFilter>().sharedMesh;
|
||||
}
|
||||
|
||||
SkinnedMeshRenderer skinMesh = gameObject.GetComponent<SkinnedMeshRenderer>();
|
||||
if (skinMesh)
|
||||
{
|
||||
if (!ExportAnimations && settings.BakeSkinnedMeshes)
|
||||
{
|
||||
if (!_bakedMeshes.ContainsKey(skinMesh))
|
||||
{
|
||||
UnityEngine.Mesh bakedMesh = new UnityEngine.Mesh();
|
||||
skinMesh.BakeMesh(bakedMesh);
|
||||
_bakedMeshes.Add(skinMesh, bakedMesh);
|
||||
}
|
||||
|
||||
return _bakedMeshes[skinMesh];
|
||||
}
|
||||
|
||||
return gameObject.GetComponent<SkinnedMeshRenderer>().sharedMesh;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private UnityEngine.Material[] GetMaterialsFromGameObject(GameObject gameObject)
|
||||
{
|
||||
if (gameObject.GetComponent<MeshRenderer>())
|
||||
{
|
||||
return gameObject.GetComponent<MeshRenderer>().sharedMaterials;
|
||||
}
|
||||
|
||||
if (gameObject.GetComponent<SkinnedMeshRenderer>())
|
||||
{
|
||||
return gameObject.GetComponent<SkinnedMeshRenderer>().sharedMaterials;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private Vector4[] boneWeightToBoneVec4(BoneWeight[] bw)
|
||||
{
|
||||
Vector4[] bones = new Vector4[bw.Length];
|
||||
for (int i = 0; i < bw.Length; ++i)
|
||||
{
|
||||
bones[i] = new Vector4(bw[i].boneIndex0, bw[i].boneIndex1, bw[i].boneIndex2, bw[i].boneIndex3);
|
||||
}
|
||||
|
||||
return bones;
|
||||
}
|
||||
|
||||
private Vector4[] boneWeightToWeightVec4(BoneWeight[] bw)
|
||||
{
|
||||
Vector4[] weights = new Vector4[bw.Length];
|
||||
for (int i = 0; i < bw.Length; ++i)
|
||||
{
|
||||
weights[i] = new Vector4(bw[i].weight0, bw[i].weight1, bw[i].weight2, bw[i].weight3);
|
||||
}
|
||||
|
||||
return weights;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fb74840032dc4385aea8ea2f67c3d17e
|
||||
timeCreated: 1657012764
|
||||
@@ -0,0 +1,789 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using GLTF.Schema;
|
||||
using UnityEngine;
|
||||
using UnityGLTF.Cache;
|
||||
using Object = UnityEngine.Object;
|
||||
using WrapMode = GLTF.Schema.WrapMode;
|
||||
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
#endif
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public partial class GLTFSceneExporter
|
||||
{
|
||||
private string GetUniqueName(HashSet<string> existingNames, string name)
|
||||
{
|
||||
if (!existingNames.Contains(name)) return name;
|
||||
var i = 1;
|
||||
while (existingNames.Contains(name + "-" + i))
|
||||
i++;
|
||||
return name + "-" + i;
|
||||
}
|
||||
|
||||
private void ExportImages(string outputPath)
|
||||
{
|
||||
var allPaths = new HashSet<string>();
|
||||
for (int t = 0; t < _imageInfos.Count; ++t)
|
||||
{
|
||||
writeImageToDiskMarker.Begin();
|
||||
|
||||
var image = _imageInfos[t].texture;
|
||||
var textureMapType = _imageInfos[t].textureMapType;
|
||||
var fileOutputPath = Path.Combine(outputPath, GetUniqueName(allPaths, _imageInfos[t].outputPath));
|
||||
allPaths.Add(fileOutputPath);
|
||||
|
||||
var canBeExportedFromDisk = _imageInfos[t].canBeExportedFromDisk;
|
||||
|
||||
var dir = Path.GetDirectoryName(fileOutputPath);
|
||||
if (!Directory.Exists(dir) && dir != null)
|
||||
Directory.CreateDirectory(dir);
|
||||
|
||||
bool wasAbleToExportTexture = false;
|
||||
if (canBeExportedFromDisk)
|
||||
{
|
||||
File.WriteAllBytes(fileOutputPath, GetTextureDataFromDisk(image));
|
||||
}
|
||||
|
||||
if (!wasAbleToExportTexture)
|
||||
{
|
||||
switch (textureMapType.conversion)
|
||||
{
|
||||
case TextureExportSettings.Conversion.MetalGlossChannelSwap:
|
||||
ExportLinearTexture(image, fileOutputPath, true);
|
||||
break;
|
||||
case TextureExportSettings.Conversion.None:
|
||||
if (textureMapType.linear)
|
||||
ExportLinearTexture(image, fileOutputPath, false);
|
||||
else
|
||||
ExportTexture(image, fileOutputPath);
|
||||
break;
|
||||
case TextureExportSettings.Conversion.NormalChannel:
|
||||
ExportNormalTexture(image, fileOutputPath);
|
||||
break;
|
||||
default:
|
||||
ExportTexture(image, fileOutputPath);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
writeImageToDiskMarker.End();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This converts Unity's metallic-gloss texture representation into GLTF's metallic-roughness specifications.
|
||||
/// Unity's metallic-gloss A channel (glossiness) is inverted and goes into GLTF's metallic-roughness G channel (roughness).
|
||||
/// Unity's metallic-gloss R channel (metallic) goes into GLTF's metallic-roughess B channel.
|
||||
/// </summary>
|
||||
/// <param name="texture">Unity's metallic-gloss texture to be exported</param>
|
||||
/// <param name="outputPath">The location to export the texture</param>
|
||||
private void ExportLinearTexture(Texture2D texture, string outputPath, bool swapMetalGlossChannels)
|
||||
{
|
||||
if (!texture)
|
||||
{
|
||||
UnityEngine.Debug.LogError("Can not export missing texture: " + outputPath);
|
||||
return;
|
||||
}
|
||||
var destRenderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
|
||||
if (swapMetalGlossChannels)
|
||||
Graphics.Blit(texture, destRenderTexture, _metalGlossChannelSwapMaterial);
|
||||
else
|
||||
Graphics.Blit(texture, destRenderTexture);
|
||||
WriteRenderTextureToDiskAndRelease(destRenderTexture, outputPath, true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This export's the normal texture. If a texture is marked as a normal map, the values are stored in the A and G channel.
|
||||
/// To output the correct normal texture, the A channel is put into the R channel.
|
||||
/// </summary>
|
||||
/// <param name="texture">Unity's normal texture to be exported</param>
|
||||
/// <param name="outputPath">The location to export the texture</param>
|
||||
private void ExportNormalTexture(Texture2D texture, string outputPath)
|
||||
{
|
||||
var destRenderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
|
||||
var wr = GL.sRGBWrite;
|
||||
GL.sRGBWrite = false;
|
||||
Graphics.Blit(texture, destRenderTexture, _normalChannelMaterial);
|
||||
WriteRenderTextureToDiskAndRelease(destRenderTexture, outputPath, true);
|
||||
GL.sRGBWrite = wr;
|
||||
}
|
||||
|
||||
private void ExportTexture(Texture2D texture, string outputPath)
|
||||
{
|
||||
var destRenderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
|
||||
Graphics.Blit(texture, destRenderTexture);
|
||||
WriteRenderTextureToDiskAndRelease(destRenderTexture, outputPath, false);
|
||||
}
|
||||
|
||||
private void WriteRenderTextureToDiskAndRelease(RenderTexture destRenderTexture, string outputPath, bool linear)
|
||||
{
|
||||
RenderTexture.active = destRenderTexture;
|
||||
|
||||
var exportTexture = new Texture2D(destRenderTexture.width, destRenderTexture.height, TextureFormat.ARGB32, false, linear);
|
||||
exportTexture.ReadPixels(new Rect(0, 0, destRenderTexture.width, destRenderTexture.height), 0, 0);
|
||||
exportTexture.Apply();
|
||||
|
||||
var binaryData = outputPath.EndsWith(".jpg") ? exportTexture.EncodeToJPG(settings.DefaultJpegQuality) : exportTexture.EncodeToPNG();
|
||||
File.WriteAllBytes(outputPath, binaryData);
|
||||
|
||||
RenderTexture.ReleaseTemporary(destRenderTexture);
|
||||
if (Application.isEditor)
|
||||
Object.DestroyImmediate(exportTexture);
|
||||
else
|
||||
Object.Destroy(exportTexture);
|
||||
}
|
||||
|
||||
public TextureInfo ExportTextureInfo(Texture texture, string textureSlot, TextureExportSettings exportSettings = default)
|
||||
{
|
||||
var info = new TextureInfo();
|
||||
|
||||
info.Index = ExportTexture(texture, textureSlot, exportSettings);
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
public TextureId ExportTexture(Texture textureObj, string textureSlot, TextureExportSettings exportSettings = default)
|
||||
{
|
||||
var uniqueTexture = exportSettings.isValid ?
|
||||
new UniqueTexture(textureObj, exportSettings) :
|
||||
new UniqueTexture(textureObj, textureSlot, this);
|
||||
|
||||
_exportOptions.BeforeTextureExport?.Invoke(this, ref uniqueTexture, textureSlot);
|
||||
|
||||
TextureId id = GetTextureId(_root, uniqueTexture);
|
||||
if (id != null)
|
||||
{
|
||||
return id;
|
||||
}
|
||||
|
||||
var texture = new GLTFTexture();
|
||||
|
||||
//If texture name not set give it a unique name using count
|
||||
if (textureObj.name == "")
|
||||
{
|
||||
textureObj.name = (_root.Textures.Count + 1).ToString();
|
||||
}
|
||||
|
||||
if (settings.ExportNames)
|
||||
{
|
||||
texture.Name = textureObj.name;
|
||||
}
|
||||
|
||||
if (_shouldUseInternalBufferForImages)
|
||||
{
|
||||
texture.Source = ExportImageInternalBuffer(uniqueTexture, textureSlot);
|
||||
}
|
||||
else
|
||||
{
|
||||
texture.Source = ExportImage(uniqueTexture, textureSlot);
|
||||
}
|
||||
texture.Sampler = ExportSampler(textureObj);
|
||||
|
||||
_textures.Add(uniqueTexture);
|
||||
|
||||
id = new TextureId
|
||||
{
|
||||
Id = _root.Textures.Count,
|
||||
Root = _root
|
||||
};
|
||||
|
||||
_root.Textures.Add(texture);
|
||||
|
||||
// HACK we should properly check if the above texture was exported as EXR and then treat it differently;
|
||||
// this here assumes the texture is already readable / was read back
|
||||
if (textureSlot == TextureMapType.Custom_HDR)
|
||||
{
|
||||
if (texture.Extensions == null) texture.Extensions = new Dictionary<string, IExtension>();
|
||||
texture.Extensions.Add(EXT_texture_exr.EXTENSION_NAME, new EXT_texture_exr(texture.Source));
|
||||
DeclareExtensionUsage(EXT_texture_exr.EXTENSION_NAME);
|
||||
}
|
||||
|
||||
_exportOptions.AfterTextureExport?.Invoke(this, uniqueTexture, id.Id, texture);
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Used for determining the resulting file output path for external images (not internal buffer).
|
||||
/// Depends on various factors such as alpha channel, texture map type / conversion needs, and existing data on disk.
|
||||
/// Logic needs to match the one in ExportImageInternalBuffer.
|
||||
/// The actual export happens in ExportImages.
|
||||
/// </summary>
|
||||
/// <returns>The relative texture output path on disk, including extension</returns>
|
||||
private string GetImageOutputPath(Texture texture, TextureExportSettings textureMapType, string textureSlot, out bool ableToExportFromDisk)
|
||||
{
|
||||
var imagePath = _exportOptions.TexturePathRetriever(texture);
|
||||
if (string.IsNullOrEmpty(imagePath))
|
||||
{
|
||||
imagePath = texture.name;
|
||||
}
|
||||
|
||||
ableToExportFromDisk = false;
|
||||
bool textureHasAlpha = true;
|
||||
|
||||
if (settings.TryExportTexturesFromDisk && CanGetTextureDataFromDisk(textureMapType, texture, out string path))
|
||||
{
|
||||
if (IsPng(path) || IsJpeg(path))
|
||||
{
|
||||
imagePath = path;
|
||||
ableToExportFromDisk = true;
|
||||
}
|
||||
}
|
||||
|
||||
switch (textureMapType.alphaMode)
|
||||
{
|
||||
case TextureExportSettings.AlphaMode.Never:
|
||||
textureHasAlpha = false;
|
||||
break;
|
||||
case TextureExportSettings.AlphaMode.Heuristic:
|
||||
textureHasAlpha = TextureHasAlphaChannel(texture);
|
||||
break;
|
||||
}
|
||||
|
||||
var canExportAsJpeg = !textureHasAlpha && settings.UseTextureFileTypeHeuristic;
|
||||
var desiredExtension = canExportAsJpeg ? ".jpg" : ".png";
|
||||
if (textureSlot == TextureMapType.Custom_HDR)
|
||||
desiredExtension = ".exr";
|
||||
|
||||
if (!settings.ExportFullPath)
|
||||
{
|
||||
imagePath = Path.GetFileName(imagePath);
|
||||
}
|
||||
|
||||
if (!ableToExportFromDisk)
|
||||
{
|
||||
imagePath = Path.ChangeExtension(imagePath, desiredExtension);
|
||||
}
|
||||
|
||||
return imagePath;
|
||||
}
|
||||
|
||||
private ImageId ExportImage(UniqueTexture uniqueTexture, string textureSlot)
|
||||
{
|
||||
var texture = uniqueTexture.Texture;
|
||||
var width = uniqueTexture.GetWidth();
|
||||
var height = uniqueTexture.GetHeight();
|
||||
|
||||
ImageId id = GetImageId(_root, texture, uniqueTexture.ExportSettings);
|
||||
if (id != null)
|
||||
{
|
||||
return id;
|
||||
}
|
||||
|
||||
var image = new GLTFImage();
|
||||
|
||||
if (ExportNames)
|
||||
{
|
||||
image.Name = texture.name;
|
||||
}
|
||||
|
||||
if (texture.GetType() == typeof(RenderTexture))
|
||||
{
|
||||
Texture2D tempTexture = new Texture2D(width, height);
|
||||
tempTexture.name = texture.name;
|
||||
|
||||
RenderTexture.active = texture as RenderTexture;
|
||||
tempTexture.ReadPixels(new Rect(0, 0, width, height), 0, 0);
|
||||
tempTexture.Apply();
|
||||
texture = tempTexture;
|
||||
}
|
||||
|
||||
#if UNITY_2017_1_OR_NEWER
|
||||
if (texture.GetType() == typeof(CustomRenderTexture))
|
||||
{
|
||||
Texture2D tempTexture = new Texture2D(width, height);
|
||||
tempTexture.name = texture.name;
|
||||
|
||||
RenderTexture.active = texture as CustomRenderTexture;
|
||||
tempTexture.ReadPixels(new Rect(0, 0, width, height), 0, 0);
|
||||
tempTexture.Apply();
|
||||
texture = tempTexture;
|
||||
}
|
||||
#endif
|
||||
|
||||
var filenamePath = GetImageOutputPath(texture, uniqueTexture.ExportSettings, textureSlot, out var canBeExportedFromDisk);
|
||||
|
||||
// some characters such as # are allowed as part of an URI and are thus not escaped
|
||||
// by EscapeUriString. They need to be escaped if they're part of the filename though.
|
||||
image.Uri = Path.Combine(
|
||||
Uri.EscapeUriString(Path.GetDirectoryName(filenamePath).Replace("\\","/")),
|
||||
Uri.EscapeDataString(Path.GetFileName(filenamePath))
|
||||
).Replace("\\","/");
|
||||
|
||||
// TODO: handle cubemap export
|
||||
var imageInfoTexture = texture as Texture2D;
|
||||
_imageInfos.Add(new ImageInfo
|
||||
{
|
||||
texture = imageInfoTexture,
|
||||
textureMapType = uniqueTexture.ExportSettings,
|
||||
outputPath = filenamePath,
|
||||
canBeExportedFromDisk = canBeExportedFromDisk,
|
||||
});
|
||||
|
||||
id = new ImageId
|
||||
{
|
||||
Id = _root.Images.Count,
|
||||
Root = _root
|
||||
};
|
||||
|
||||
_root.Images.Add(image);
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
private bool CanGetTextureDataFromDisk(TextureExportSettings textureMapType, Texture texture, out string path)
|
||||
{
|
||||
path = null;
|
||||
|
||||
#if UNITY_EDITOR
|
||||
if (Application.isEditor && UnityEditor.AssetDatabase.Contains(texture))
|
||||
{
|
||||
path = UnityEditor.AssetDatabase.GetAssetPath(texture);
|
||||
var importer = AssetImporter.GetAtPath(path) as TextureImporter;
|
||||
if (importer?.textureShape != TextureImporterShape.Texture2D)
|
||||
return false;
|
||||
|
||||
switch (textureMapType.conversion)
|
||||
{
|
||||
// if this is a normal map generated from greyscale, we shouldn't attempt to export from disk
|
||||
case TextureExportSettings.Conversion.NormalChannel:
|
||||
if (importer && importer.textureType == TextureImporterType.NormalMap && importer.convertToNormalmap)
|
||||
return false;
|
||||
break;
|
||||
// check if the texture contains an alpha channel; if yes, we shouldn't attempt to export from disk but instead convert.
|
||||
case TextureExportSettings.Conversion.MetalGlossChannelSwap:
|
||||
if (importer && importer.DoesSourceTextureHaveAlpha())
|
||||
return false;
|
||||
break;
|
||||
}
|
||||
|
||||
if (File.Exists(path))
|
||||
{
|
||||
if(AssetDatabase.GetMainAssetTypeAtPath(path) != typeof(Texture2D))
|
||||
{
|
||||
var ext = Path.GetExtension(path);
|
||||
path = path.Replace(ext, "-" + texture.name + ext);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
private byte[] GetTextureDataFromDisk(Texture texture)
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
var path = UnityEditor.AssetDatabase.GetAssetPath(texture);
|
||||
|
||||
if (File.Exists(path))
|
||||
return File.ReadAllBytes(path);
|
||||
#endif
|
||||
return null;
|
||||
}
|
||||
|
||||
bool TextureHasAlphaChannel(Texture sourceTexture)
|
||||
{
|
||||
var hasAlpha = false;
|
||||
|
||||
#if UNITY_EDITOR
|
||||
if (AssetDatabase.Contains(sourceTexture) && sourceTexture is Texture2D)
|
||||
{
|
||||
var importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(sourceTexture)) as TextureImporter;
|
||||
if (importer)
|
||||
{
|
||||
switch (importer.alphaSource)
|
||||
{
|
||||
case TextureImporterAlphaSource.FromInput:
|
||||
hasAlpha = importer.DoesSourceTextureHaveAlpha();
|
||||
break;
|
||||
case TextureImporterAlphaSource.FromGrayScale:
|
||||
hasAlpha = true;
|
||||
break;
|
||||
case TextureImporterAlphaSource.None:
|
||||
hasAlpha = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
UnityEngine.Experimental.Rendering.GraphicsFormat graphicsFormat = UnityEngine.Experimental.Rendering.GraphicsFormat.None;
|
||||
#if !UNITY_2019_1_OR_NEWER
|
||||
if (sourceTexture is Texture2D tex2D)
|
||||
graphicsFormat = UnityEngine.Experimental.Rendering.GraphicsFormatUtility.GetGraphicsFormat(tex2D.format, true);
|
||||
#else
|
||||
graphicsFormat = sourceTexture.graphicsFormat;
|
||||
#endif
|
||||
#if UNITY_2018_2_OR_NEWER
|
||||
if(graphicsFormat != UnityEngine.Experimental.Rendering.GraphicsFormat.None)
|
||||
hasAlpha |= UnityEngine.Experimental.Rendering.GraphicsFormatUtility.HasAlphaChannel(graphicsFormat);
|
||||
#else
|
||||
hasAlpha = true;
|
||||
#endif
|
||||
return hasAlpha;
|
||||
}
|
||||
|
||||
private bool IsPng(string filename)
|
||||
{
|
||||
return Path.GetExtension(filename).EndsWith("png", StringComparison.InvariantCultureIgnoreCase);
|
||||
}
|
||||
|
||||
private bool IsJpeg(string filename)
|
||||
{
|
||||
return Path.GetExtension(filename).EndsWith("jpg", StringComparison.InvariantCultureIgnoreCase) || Path.GetExtension(filename).EndsWith("jpeg", StringComparison.InvariantCultureIgnoreCase);
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
private bool TryGetImporter<T>(Object obj, out T importer) where T : AssetImporter
|
||||
{
|
||||
if (EditorUtility.IsPersistent(obj))
|
||||
{
|
||||
var texturePath = AssetDatabase.GetAssetPath(obj);
|
||||
importer = AssetImporter.GetAtPath(texturePath) as T;
|
||||
return importer;
|
||||
}
|
||||
importer = null;
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
|
||||
private ImageId ExportImageInternalBuffer(UniqueTexture uniqueTexture, string textureSlot)
|
||||
{
|
||||
var texture = uniqueTexture.Texture;
|
||||
var exportSettings = uniqueTexture.ExportSettings;
|
||||
|
||||
const string PNGMimeType = "image/png";
|
||||
const string JPEGMimeType = "image/jpeg";
|
||||
|
||||
if (texture == null)
|
||||
{
|
||||
throw new NullReferenceException("texture can not be NULL.");
|
||||
}
|
||||
|
||||
var image = new GLTFImage();
|
||||
image.MimeType = PNGMimeType;
|
||||
|
||||
AlignToBoundary(_bufferWriter.BaseStream, 0x00);
|
||||
uint byteOffset = CalculateAlignment((uint)_bufferWriter.BaseStream.Position, 4);
|
||||
|
||||
bool wasAbleToExport = false;
|
||||
bool textureHasAlpha = true;
|
||||
|
||||
if (settings.TryExportTexturesFromDisk && CanGetTextureDataFromDisk(exportSettings, texture, out string path))
|
||||
{
|
||||
if (IsPng(path))
|
||||
{
|
||||
image.MimeType = PNGMimeType;
|
||||
var imageBytes = GetTextureDataFromDisk(texture);
|
||||
_bufferWriter.Write(imageBytes);
|
||||
wasAbleToExport = true;
|
||||
}
|
||||
else if (IsJpeg(path))
|
||||
{
|
||||
image.MimeType = JPEGMimeType;
|
||||
var imageBytes = GetTextureDataFromDisk(texture);
|
||||
_bufferWriter.Write(imageBytes);
|
||||
wasAbleToExport = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Log("Texture can't be exported from disk: " + path + ". Only PNG & JPEG are supported. The texture will be re-encoded as PNG.", texture);
|
||||
}
|
||||
}
|
||||
|
||||
// export in-memory floating point textures as EXR
|
||||
// TODO add readback when not readable
|
||||
if (!wasAbleToExport && textureSlot == TextureMapType.Custom_HDR)
|
||||
{
|
||||
byte[] exrImageData = default;
|
||||
|
||||
if (texture.isReadable)
|
||||
{
|
||||
const Texture2D.EXRFlags EXR_Flags = Texture2D.EXRFlags.CompressZIP;
|
||||
|
||||
if (texture is Texture2D texture2D)
|
||||
{
|
||||
exrImageData = texture2D.EncodeToEXR(EXR_Flags);
|
||||
}
|
||||
else if (texture is RenderTexture rt)
|
||||
{
|
||||
var prev = RenderTexture.active;
|
||||
RenderTexture.active = rt;
|
||||
var temp = new Texture2D(rt.width, rt.height, TextureFormat.RGBAFloat, false, true);
|
||||
temp.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
|
||||
temp.Apply();
|
||||
RenderTexture.active = prev;
|
||||
exrImageData = temp.EncodeToEXR(EXR_Flags);
|
||||
}
|
||||
}
|
||||
|
||||
if (exrImageData != null)
|
||||
{
|
||||
image.MimeType = "image/exr";
|
||||
_bufferWriter.Write(exrImageData);
|
||||
wasAbleToExport = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!wasAbleToExport)
|
||||
{
|
||||
var sRGB = !exportSettings.linear;
|
||||
|
||||
#if UNITY_EDITOR
|
||||
if (textureSlot == TextureMapType.Custom_Unknown)
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
if (TryGetImporter<TextureImporter>(texture, out var importer))
|
||||
{
|
||||
if (!importer.sRGBTexture)
|
||||
sRGB = false;
|
||||
else
|
||||
sRGB = true;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
var format = sRGB ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear;
|
||||
|
||||
var width = uniqueTexture.GetWidth();
|
||||
var height = uniqueTexture.GetHeight();
|
||||
|
||||
// TODO we could make sure texture size is power-of-two here
|
||||
|
||||
switch (exportSettings.alphaMode)
|
||||
{
|
||||
case TextureExportSettings.AlphaMode.Never:
|
||||
textureHasAlpha = false;
|
||||
break;
|
||||
case TextureExportSettings.AlphaMode.Always:
|
||||
textureHasAlpha = true;
|
||||
break;
|
||||
case TextureExportSettings.AlphaMode.Heuristic:
|
||||
textureHasAlpha = TextureHasAlphaChannel(texture);
|
||||
break;
|
||||
}
|
||||
|
||||
if (textureSlot == TextureMapType.Custom_HDR)
|
||||
{
|
||||
Debug.LogWarning("HDR Texture Export from non-readable textures isn't supported yet", texture);
|
||||
}
|
||||
|
||||
|
||||
var canExportAsJpeg = !textureHasAlpha && settings.UseTextureFileTypeHeuristic;
|
||||
image.MimeType = canExportAsJpeg ? JPEGMimeType : PNGMimeType;
|
||||
|
||||
var cacheKey = uniqueTexture.GetHashCode().ToString();
|
||||
if (settings.UseCaching && ExportCache.TryGetBytes(texture, cacheKey, out var bytes))
|
||||
{
|
||||
_bufferWriter.Write(bytes);
|
||||
}
|
||||
else
|
||||
{
|
||||
var destRenderTexture = RenderTexture.GetTemporary(width, height, 24, RenderTextureFormat.Default, format);
|
||||
var previousSRGBState = GL.sRGBWrite;
|
||||
GL.sRGBWrite = sRGB;
|
||||
|
||||
var shader = GetConversionMaterial(exportSettings);
|
||||
if (shader && shader.HasProperty("_SmoothnessMultiplier"))
|
||||
shader.SetFloat("_SmoothnessMultiplier", exportSettings.smoothnessMultiplier);
|
||||
|
||||
if (shader)
|
||||
Graphics.Blit(texture, destRenderTexture, shader);
|
||||
else
|
||||
Graphics.Blit(texture, destRenderTexture);
|
||||
|
||||
var exportTexture = new Texture2D(width, height, TextureFormat.ARGB32, false, false);
|
||||
exportTexture.ReadPixels(new Rect(0, 0, destRenderTexture.width, destRenderTexture.height), 0, 0);
|
||||
exportTexture.Apply();
|
||||
|
||||
var imageData = canExportAsJpeg ? exportTexture.EncodeToJPG(settings.DefaultJpegQuality) : exportTexture.EncodeToPNG();
|
||||
_bufferWriter.Write(imageData);
|
||||
|
||||
if (settings.UseCaching)
|
||||
ExportCache.AddBytes(texture, cacheKey, imageData);
|
||||
|
||||
GL.sRGBWrite = previousSRGBState;
|
||||
|
||||
RenderTexture.ReleaseTemporary(destRenderTexture);
|
||||
|
||||
if (Application.isEditor)
|
||||
{
|
||||
UnityEngine.Object.DestroyImmediate(exportTexture);
|
||||
}
|
||||
else
|
||||
{
|
||||
UnityEngine.Object.Destroy(exportTexture);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
// // Check for potential warnings in GLTF validation
|
||||
// if (!Mathf.IsPowerOfTwo(texture.width) || !Mathf.IsPowerOfTwo(texture.height))
|
||||
// {
|
||||
// Debug.LogWarning("Validation Warning: " + "Image has non-power-of-two dimensions: " + texture.width + "x" + texture.height + ".", texture);
|
||||
// }
|
||||
|
||||
uint byteLength = CalculateAlignment((uint)_bufferWriter.BaseStream.Position - byteOffset, 4);
|
||||
image.BufferView = ExportBufferView((uint)byteOffset, (uint)byteLength);
|
||||
|
||||
if (ExportNames)
|
||||
{
|
||||
image.Name = texture.name;
|
||||
}
|
||||
|
||||
var id = new ImageId
|
||||
{
|
||||
Id = _root.Images.Count,
|
||||
Root = _root
|
||||
};
|
||||
_root.Images.Add(image);
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
private struct SamplerRelevantTextureData : IEquatable<SamplerRelevantTextureData>
|
||||
{
|
||||
private readonly TextureWrapMode wrapMode;
|
||||
private readonly FilterMode filterMode;
|
||||
private readonly bool hasMipmaps;
|
||||
private readonly bool hasAniso;
|
||||
public bool HasMipmaps => hasMipmaps;
|
||||
public bool HasAniso => hasAniso;
|
||||
|
||||
public SamplerRelevantTextureData(Texture texture)
|
||||
{
|
||||
var mipmapCount = 1;
|
||||
var aniso = 1;
|
||||
#if UNITY_2019_2_OR_NEWER
|
||||
mipmapCount = texture.mipmapCount;
|
||||
aniso = texture.anisoLevel;
|
||||
#else
|
||||
if (texture is Texture2D tex2D) mipmapCount = tex2D.mipmapCount;
|
||||
#endif
|
||||
wrapMode = texture.wrapMode;
|
||||
filterMode = texture.filterMode;
|
||||
hasMipmaps = mipmapCount > 1;
|
||||
hasAniso = aniso > 0;
|
||||
}
|
||||
|
||||
public bool Equals(SamplerRelevantTextureData other)
|
||||
{
|
||||
return wrapMode == other.wrapMode && filterMode == other.filterMode && hasMipmaps == other.hasMipmaps && hasAniso == other.hasAniso;
|
||||
}
|
||||
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
return obj is SamplerRelevantTextureData other && Equals(other);
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
unchecked
|
||||
{
|
||||
var hashCode = (int)wrapMode;
|
||||
hashCode = (hashCode * 397) ^ (int)filterMode;
|
||||
hashCode = (hashCode * 397) ^ hasMipmaps.GetHashCode();
|
||||
hashCode = (hashCode * 397) ^ hasAniso.GetHashCode();
|
||||
return hashCode;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Dictionary<SamplerRelevantTextureData, int> _textureSettingsToSamplerIndices =
|
||||
new Dictionary<SamplerRelevantTextureData, int>();
|
||||
private SamplerId ExportSampler(Texture texture)
|
||||
{
|
||||
var dataForTexture = new SamplerRelevantTextureData(texture);
|
||||
|
||||
if (_textureSettingsToSamplerIndices.TryGetValue(dataForTexture, out var existingSamplerIndex))
|
||||
{
|
||||
return new SamplerId
|
||||
{
|
||||
Id = existingSamplerIndex,
|
||||
Root = _root
|
||||
};
|
||||
}
|
||||
|
||||
var sampler = new Sampler();
|
||||
|
||||
switch (texture.wrapMode)
|
||||
{
|
||||
case TextureWrapMode.Clamp:
|
||||
sampler.WrapS = WrapMode.ClampToEdge;
|
||||
sampler.WrapT = WrapMode.ClampToEdge;
|
||||
break;
|
||||
case TextureWrapMode.Repeat:
|
||||
sampler.WrapS = WrapMode.Repeat;
|
||||
sampler.WrapT = WrapMode.Repeat;
|
||||
break;
|
||||
case TextureWrapMode.Mirror:
|
||||
sampler.WrapS = WrapMode.MirroredRepeat;
|
||||
sampler.WrapT = WrapMode.MirroredRepeat;
|
||||
break;
|
||||
default:
|
||||
Debug.LogWarning("Unsupported Texture.wrapMode: " + texture.wrapMode, texture);
|
||||
sampler.WrapS = WrapMode.Repeat;
|
||||
sampler.WrapT = WrapMode.Repeat;
|
||||
break;
|
||||
}
|
||||
|
||||
if(dataForTexture.HasMipmaps)
|
||||
{
|
||||
switch (texture.filterMode)
|
||||
{
|
||||
case FilterMode.Point:
|
||||
sampler.MinFilter = MinFilterMode.NearestMipmapNearest;
|
||||
sampler.MagFilter = MagFilterMode.Nearest;
|
||||
break;
|
||||
case FilterMode.Bilinear:
|
||||
// not technically correct but matches result in Unity much better. When any aniso is on, the expectation is a smooth texture transition.
|
||||
sampler.MinFilter = dataForTexture.HasAniso ? MinFilterMode.LinearMipmapLinear : MinFilterMode.LinearMipmapNearest;
|
||||
sampler.MagFilter = MagFilterMode.Linear;
|
||||
break;
|
||||
case FilterMode.Trilinear:
|
||||
sampler.MinFilter = MinFilterMode.LinearMipmapLinear;
|
||||
sampler.MagFilter = MagFilterMode.Linear;
|
||||
break;
|
||||
default:
|
||||
Debug.LogWarning("Unsupported Texture.filterMode: " + texture.filterMode, texture);
|
||||
sampler.MinFilter = MinFilterMode.LinearMipmapLinear;
|
||||
sampler.MagFilter = MagFilterMode.Linear;
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (texture.filterMode)
|
||||
{
|
||||
case FilterMode.Point:
|
||||
sampler.MinFilter = MinFilterMode.Nearest;
|
||||
sampler.MagFilter = MagFilterMode.Nearest;
|
||||
break;
|
||||
default:
|
||||
sampler.MinFilter = MinFilterMode.Linear;
|
||||
sampler.MagFilter = MagFilterMode.Linear;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var samplerId = new SamplerId
|
||||
{
|
||||
Id = _root.Samplers.Count,
|
||||
Root = _root
|
||||
};
|
||||
|
||||
_root.Samplers.Add(sampler);
|
||||
_textureSettingsToSamplerIndices.Add(dataForTexture, samplerId.Id);
|
||||
|
||||
return samplerId;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e2d7fb34285a479db4c18291fe881855
|
||||
timeCreated: 1657010903
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4903dfef32b84dd2862485b344995895
|
||||
timeCreated: 1657012079
|
||||
@@ -0,0 +1,346 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GLTF;
|
||||
using GLTF.Schema;
|
||||
using UnityEngine;
|
||||
using UnityGLTF.Cache;
|
||||
using UnityGLTF.Extensions;
|
||||
|
||||
namespace UnityGLTF
|
||||
{
|
||||
public partial class GLTFSceneImporter
|
||||
{
|
||||
#if UNITY_ANIMATION || !UNITY_2019_1_OR_NEWER
|
||||
private static string RelativePathFrom(Transform self, Transform root)
|
||||
{
|
||||
var path = new List<String>();
|
||||
for (var current = self; current != null; current = current.parent)
|
||||
{
|
||||
if (current == root)
|
||||
{
|
||||
return String.Join("/", path.ToArray());
|
||||
}
|
||||
|
||||
path.Insert(0, current.name);
|
||||
}
|
||||
|
||||
throw new Exception("no RelativePath");
|
||||
}
|
||||
|
||||
protected virtual async Task BuildAnimationSamplers(GLTFAnimation animation, int animationId)
|
||||
{
|
||||
// look up expected data types
|
||||
var typeMap = new Dictionary<int, string>();
|
||||
foreach (var channel in animation.Channels)
|
||||
{
|
||||
typeMap[channel.Sampler.Id] = channel.Target.Path.ToString();
|
||||
}
|
||||
|
||||
var samplers = _assetCache.AnimationCache[animationId].Samplers;
|
||||
var samplersByType = new Dictionary<string, List<AttributeAccessor>>
|
||||
{
|
||||
{"time", new List<AttributeAccessor>(animation.Samplers.Count)}
|
||||
};
|
||||
|
||||
for (var i = 0; i < animation.Samplers.Count; i++)
|
||||
{
|
||||
// no sense generating unused samplers
|
||||
if (!typeMap.ContainsKey(i))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var samplerDef = animation.Samplers[i];
|
||||
|
||||
samplers[i].Interpolation = samplerDef.Interpolation;
|
||||
|
||||
// set up input accessors
|
||||
BufferCacheData inputBufferCacheData = await GetBufferData(samplerDef.Input.Value.BufferView.Value.Buffer);
|
||||
AttributeAccessor attributeAccessor = new AttributeAccessor
|
||||
{
|
||||
AccessorId = samplerDef.Input,
|
||||
Stream = inputBufferCacheData.Stream,
|
||||
Offset = inputBufferCacheData.ChunkOffset
|
||||
};
|
||||
|
||||
samplers[i].Input = attributeAccessor;
|
||||
samplersByType["time"].Add(attributeAccessor);
|
||||
|
||||
// set up output accessors
|
||||
BufferCacheData outputBufferCacheData = await GetBufferData(samplerDef.Output.Value.BufferView.Value.Buffer);
|
||||
attributeAccessor = new AttributeAccessor
|
||||
{
|
||||
AccessorId = samplerDef.Output,
|
||||
Stream = outputBufferCacheData.Stream,
|
||||
Offset = outputBufferCacheData.ChunkOffset
|
||||
};
|
||||
|
||||
samplers[i].Output = attributeAccessor;
|
||||
|
||||
if (!samplersByType.ContainsKey(typeMap[i]))
|
||||
{
|
||||
samplersByType[typeMap[i]] = new List<AttributeAccessor>();
|
||||
}
|
||||
|
||||
samplersByType[typeMap[i]].Add(attributeAccessor);
|
||||
}
|
||||
|
||||
// populate attributeAccessors with buffer data
|
||||
GLTFHelpers.BuildAnimationSamplers(ref samplersByType);
|
||||
}
|
||||
|
||||
protected void SetAnimationCurve(
|
||||
AnimationClip clip,
|
||||
string relativePath,
|
||||
string[] propertyNames,
|
||||
NumericArray input,
|
||||
NumericArray output,
|
||||
InterpolationType mode,
|
||||
Type curveType,
|
||||
ValuesConvertion getConvertedValues)
|
||||
{
|
||||
|
||||
var channelCount = propertyNames.Length;
|
||||
var frameCount = input.AsFloats.Length;
|
||||
|
||||
// copy all the key frame data to cache
|
||||
Keyframe[][] keyframes = new Keyframe[channelCount][];
|
||||
for (var ci = 0; ci < channelCount; ++ci)
|
||||
{
|
||||
keyframes[ci] = new Keyframe[frameCount];
|
||||
}
|
||||
|
||||
for (var i = 0; i < frameCount; ++i)
|
||||
{
|
||||
var time = input.AsFloats[i];
|
||||
|
||||
float[] values = null;
|
||||
float[] inTangents = null;
|
||||
float[] outTangents = null;
|
||||
if (mode == InterpolationType.CUBICSPLINE)
|
||||
{
|
||||
// For cubic spline, the output will contain 3 values per keyframe; inTangent, dataPoint, and outTangent.
|
||||
// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
|
||||
|
||||
var cubicIndex = i * 3;
|
||||
inTangents = getConvertedValues(output, cubicIndex);
|
||||
values = getConvertedValues(output, cubicIndex + 1);
|
||||
outTangents = getConvertedValues(output, cubicIndex + 2);
|
||||
}
|
||||
else
|
||||
{
|
||||
// For other interpolation types, the output will only contain one value per keyframe
|
||||
values = getConvertedValues(output, i);
|
||||
}
|
||||
|
||||
for (var ci = 0; ci < channelCount; ++ci)
|
||||
{
|
||||
if (mode == InterpolationType.CUBICSPLINE)
|
||||
{
|
||||
keyframes[ci][i] = new Keyframe(time, values[ci], inTangents[ci], outTangents[ci]);
|
||||
}
|
||||
else
|
||||
{
|
||||
keyframes[ci][i] = new Keyframe(time, values[ci]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var ci = 0; ci < channelCount; ++ci)
|
||||
{
|
||||
// copy all key frames data to animation curve and add it to the clip
|
||||
AnimationCurve curve = new AnimationCurve(keyframes[ci]);
|
||||
|
||||
// For cubic spline interpolation, the inTangents and outTangents are already explicitly defined.
|
||||
// For the rest, set them appropriately.
|
||||
if (mode != InterpolationType.CUBICSPLINE)
|
||||
{
|
||||
for (var i = 0; i < keyframes[ci].Length; i++)
|
||||
{
|
||||
SetTangentMode(curve, keyframes[ci], i, mode);
|
||||
}
|
||||
}
|
||||
clip.SetCurve(relativePath, curveType, propertyNames[ci], curve);
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetTangentMode(AnimationCurve curve, Keyframe[] keyframes, int keyframeIndex, InterpolationType interpolation)
|
||||
{
|
||||
var key = keyframes[keyframeIndex];
|
||||
|
||||
switch (interpolation)
|
||||
{
|
||||
case InterpolationType.CATMULLROMSPLINE:
|
||||
key.inTangent = 0;
|
||||
key.outTangent = 0;
|
||||
break;
|
||||
case InterpolationType.LINEAR:
|
||||
key.inTangent = GetCurveKeyframeLeftLinearSlope(keyframes, keyframeIndex);
|
||||
key.outTangent = GetCurveKeyframeLeftLinearSlope(keyframes, keyframeIndex + 1);
|
||||
break;
|
||||
case InterpolationType.STEP:
|
||||
key.inTangent = float.PositiveInfinity;
|
||||
key.outTangent = float.PositiveInfinity;
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
if(curve.length < keyframeIndex)
|
||||
curve.MoveKey(keyframeIndex, key);
|
||||
}
|
||||
|
||||
private static float GetCurveKeyframeLeftLinearSlope(Keyframe[] keyframes, int keyframeIndex)
|
||||
{
|
||||
if (keyframeIndex <= 0 || keyframeIndex >= keyframes.Length)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var valueDelta = keyframes[keyframeIndex].value - keyframes[keyframeIndex - 1].value;
|
||||
var timeDelta = keyframes[keyframeIndex].time - keyframes[keyframeIndex - 1].time;
|
||||
|
||||
if (timeDelta <= 0)
|
||||
{
|
||||
var k = keyframes[keyframeIndex];
|
||||
k.time = keyframes[keyframeIndex - 1].time + Mathf.Epsilon + 1 / 100f;
|
||||
keyframes[keyframeIndex] = k;
|
||||
Debug.Log(LogType.Warning, "Time of subsequent animation keyframes is not increasing (glTF-Validator error ACCESSOR_ANIMATION_INPUT_NON_INCREASING)");
|
||||
return float.PositiveInfinity;
|
||||
}
|
||||
return valueDelta / timeDelta;
|
||||
}
|
||||
|
||||
protected async Task<AnimationClip> ConstructClip(Transform root, int animationId, CancellationToken cancellationToken)
|
||||
{
|
||||
GLTFAnimation animation = _gltfRoot.Animations[animationId];
|
||||
|
||||
AnimationCacheData animationCache = _assetCache.AnimationCache[animationId];
|
||||
if (animationCache == null)
|
||||
{
|
||||
animationCache = new AnimationCacheData(animation.Samplers.Count);
|
||||
_assetCache.AnimationCache[animationId] = animationCache;
|
||||
}
|
||||
else if (animationCache.LoadedAnimationClip != null)
|
||||
{
|
||||
return animationCache.LoadedAnimationClip;
|
||||
}
|
||||
|
||||
// unpack accessors
|
||||
await BuildAnimationSamplers(animation, animationId);
|
||||
|
||||
// init clip
|
||||
AnimationClip clip = new AnimationClip
|
||||
{
|
||||
name = animation.Name ?? $"animation:{animationId}",
|
||||
};
|
||||
_assetCache.AnimationCache[animationId].LoadedAnimationClip = clip;
|
||||
|
||||
if (_options.AnimationMethod == AnimationMethod.Legacy)
|
||||
clip.legacy = true;
|
||||
|
||||
foreach (AnimationChannel channel in animation.Channels)
|
||||
{
|
||||
AnimationSamplerCacheData samplerCache = animationCache.Samplers[channel.Sampler.Id];
|
||||
if (channel.Target.Node == null)
|
||||
{
|
||||
// If a channel doesn't have a target node, then just skip it.
|
||||
// This is legal and is present in one of the asset generator models, but means that animation doesn't actually do anything.
|
||||
// https://github.com/KhronosGroup/glTF-Asset-Generator/tree/master/Output/Positive/Animation_NodeMisc
|
||||
// Model 08
|
||||
continue;
|
||||
}
|
||||
var node = await GetNode(channel.Target.Node.Id, cancellationToken);
|
||||
string relativePath = RelativePathFrom(node.transform, root);
|
||||
|
||||
NumericArray input = samplerCache.Input.AccessorContent,
|
||||
output = samplerCache.Output.AccessorContent;
|
||||
|
||||
string[] propertyNames;
|
||||
var known = Enum.TryParse(channel.Target.Path, out GLTFAnimationChannelPath path);
|
||||
if (!known) continue;
|
||||
switch (path)
|
||||
{
|
||||
case GLTFAnimationChannelPath.translation:
|
||||
propertyNames = new string[] { "localPosition.x", "localPosition.y", "localPosition.z" };
|
||||
|
||||
SetAnimationCurve(clip, relativePath, propertyNames, input, output,
|
||||
samplerCache.Interpolation, typeof(Transform),
|
||||
(data, frame) =>
|
||||
{
|
||||
var position = data.AsVec3s[frame].ToUnityVector3Convert();
|
||||
return new float[] { position.x, position.y, position.z };
|
||||
});
|
||||
break;
|
||||
|
||||
case GLTFAnimationChannelPath.rotation:
|
||||
propertyNames = new string[] { "localRotation.x", "localRotation.y", "localRotation.z", "localRotation.w" };
|
||||
|
||||
SetAnimationCurve(clip, relativePath, propertyNames, input, output,
|
||||
samplerCache.Interpolation, typeof(Transform),
|
||||
(data, frame) =>
|
||||
{
|
||||
var rotation = data.AsVec4s[frame];
|
||||
var quaternion = new GLTF.Math.Quaternion(rotation.X, rotation.Y, rotation.Z, rotation.W).ToUnityQuaternionConvert();
|
||||
return new float[] { quaternion.x, quaternion.y, quaternion.z, quaternion.w };
|
||||
});
|
||||
|
||||
break;
|
||||
|
||||
case GLTFAnimationChannelPath.scale:
|
||||
propertyNames = new string[] { "localScale.x", "localScale.y", "localScale.z" };
|
||||
|
||||
SetAnimationCurve(clip, relativePath, propertyNames, input, output,
|
||||
samplerCache.Interpolation, typeof(Transform),
|
||||
(data, frame) =>
|
||||
{
|
||||
var scale = data.AsVec3s[frame].ToUnityVector3Raw();
|
||||
return new float[] { scale.x, scale.y, scale.z };
|
||||
});
|
||||
break;
|
||||
|
||||
case GLTFAnimationChannelPath.weights:
|
||||
var primitives = channel.Target.Node.Value.Mesh.Value.Primitives;
|
||||
var targetCount = primitives[0].Targets.Count;
|
||||
for (int primitiveIndex = 0; primitiveIndex < primitives.Count; primitiveIndex++)
|
||||
{
|
||||
// see SceneImporter:156
|
||||
// blend shapes are always called "Morphtarget" and always have frame weight 100 on import
|
||||
|
||||
var prim = primitives[primitiveIndex];
|
||||
var targetNames = prim.TargetNames;
|
||||
propertyNames = new string[targetCount];
|
||||
for (var i = 0; i < targetCount; i++)
|
||||
propertyNames[i] = "blendShape." + (targetNames != null ? targetNames[i] : ("Morphtarget" + i));
|
||||
|
||||
var frameFloats = new float[targetCount];
|
||||
|
||||
SetAnimationCurve(clip, relativePath, propertyNames, input, output,
|
||||
samplerCache.Interpolation, typeof(SkinnedMeshRenderer),
|
||||
(data, frame) =>
|
||||
{
|
||||
var allValues = data.AsFloats;
|
||||
for (var k = 0; k < targetCount; k++)
|
||||
frameFloats[k] = allValues[frame * targetCount + k];
|
||||
|
||||
return frameFloats;
|
||||
});
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
Debug.Log(LogType.Warning, "Cannot read GLTF animation path");
|
||||
break;
|
||||
} // switch target type
|
||||
} // foreach channel
|
||||
|
||||
clip.EnsureQuaternionContinuity();
|
||||
return clip;
|
||||
}
|
||||
#endif
|
||||
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user