This commit is contained in:
左右看
2023-06-28 00:35:46 +08:00
parent cb5bab5ce9
commit 0d848e4d07
524 changed files with 78452 additions and 12 deletions
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
}
}
@@ -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);
}
}
}
@@ -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