This commit is contained in:
左右看
2023-06-28 00:35:46 +08:00
parent cb5bab5ce9
commit 0d848e4d07
524 changed files with 78452 additions and 12 deletions
@@ -0,0 +1,346 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using GLTF;
using GLTF.Schema;
using UnityEngine;
using UnityGLTF.Cache;
using UnityGLTF.Extensions;
namespace UnityGLTF
{
public partial class GLTFSceneImporter
{
#if UNITY_ANIMATION || !UNITY_2019_1_OR_NEWER
private static string RelativePathFrom(Transform self, Transform root)
{
var path = new List<String>();
for (var current = self; current != null; current = current.parent)
{
if (current == root)
{
return String.Join("/", path.ToArray());
}
path.Insert(0, current.name);
}
throw new Exception("no RelativePath");
}
protected virtual async Task BuildAnimationSamplers(GLTFAnimation animation, int animationId)
{
// look up expected data types
var typeMap = new Dictionary<int, string>();
foreach (var channel in animation.Channels)
{
typeMap[channel.Sampler.Id] = channel.Target.Path.ToString();
}
var samplers = _assetCache.AnimationCache[animationId].Samplers;
var samplersByType = new Dictionary<string, List<AttributeAccessor>>
{
{"time", new List<AttributeAccessor>(animation.Samplers.Count)}
};
for (var i = 0; i < animation.Samplers.Count; i++)
{
// no sense generating unused samplers
if (!typeMap.ContainsKey(i))
{
continue;
}
var samplerDef = animation.Samplers[i];
samplers[i].Interpolation = samplerDef.Interpolation;
// set up input accessors
BufferCacheData inputBufferCacheData = await GetBufferData(samplerDef.Input.Value.BufferView.Value.Buffer);
AttributeAccessor attributeAccessor = new AttributeAccessor
{
AccessorId = samplerDef.Input,
Stream = inputBufferCacheData.Stream,
Offset = inputBufferCacheData.ChunkOffset
};
samplers[i].Input = attributeAccessor;
samplersByType["time"].Add(attributeAccessor);
// set up output accessors
BufferCacheData outputBufferCacheData = await GetBufferData(samplerDef.Output.Value.BufferView.Value.Buffer);
attributeAccessor = new AttributeAccessor
{
AccessorId = samplerDef.Output,
Stream = outputBufferCacheData.Stream,
Offset = outputBufferCacheData.ChunkOffset
};
samplers[i].Output = attributeAccessor;
if (!samplersByType.ContainsKey(typeMap[i]))
{
samplersByType[typeMap[i]] = new List<AttributeAccessor>();
}
samplersByType[typeMap[i]].Add(attributeAccessor);
}
// populate attributeAccessors with buffer data
GLTFHelpers.BuildAnimationSamplers(ref samplersByType);
}
protected void SetAnimationCurve(
AnimationClip clip,
string relativePath,
string[] propertyNames,
NumericArray input,
NumericArray output,
InterpolationType mode,
Type curveType,
ValuesConvertion getConvertedValues)
{
var channelCount = propertyNames.Length;
var frameCount = input.AsFloats.Length;
// copy all the key frame data to cache
Keyframe[][] keyframes = new Keyframe[channelCount][];
for (var ci = 0; ci < channelCount; ++ci)
{
keyframes[ci] = new Keyframe[frameCount];
}
for (var i = 0; i < frameCount; ++i)
{
var time = input.AsFloats[i];
float[] values = null;
float[] inTangents = null;
float[] outTangents = null;
if (mode == InterpolationType.CUBICSPLINE)
{
// For cubic spline, the output will contain 3 values per keyframe; inTangent, dataPoint, and outTangent.
// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
var cubicIndex = i * 3;
inTangents = getConvertedValues(output, cubicIndex);
values = getConvertedValues(output, cubicIndex + 1);
outTangents = getConvertedValues(output, cubicIndex + 2);
}
else
{
// For other interpolation types, the output will only contain one value per keyframe
values = getConvertedValues(output, i);
}
for (var ci = 0; ci < channelCount; ++ci)
{
if (mode == InterpolationType.CUBICSPLINE)
{
keyframes[ci][i] = new Keyframe(time, values[ci], inTangents[ci], outTangents[ci]);
}
else
{
keyframes[ci][i] = new Keyframe(time, values[ci]);
}
}
}
for (var ci = 0; ci < channelCount; ++ci)
{
// copy all key frames data to animation curve and add it to the clip
AnimationCurve curve = new AnimationCurve(keyframes[ci]);
// For cubic spline interpolation, the inTangents and outTangents are already explicitly defined.
// For the rest, set them appropriately.
if (mode != InterpolationType.CUBICSPLINE)
{
for (var i = 0; i < keyframes[ci].Length; i++)
{
SetTangentMode(curve, keyframes[ci], i, mode);
}
}
clip.SetCurve(relativePath, curveType, propertyNames[ci], curve);
}
}
private static void SetTangentMode(AnimationCurve curve, Keyframe[] keyframes, int keyframeIndex, InterpolationType interpolation)
{
var key = keyframes[keyframeIndex];
switch (interpolation)
{
case InterpolationType.CATMULLROMSPLINE:
key.inTangent = 0;
key.outTangent = 0;
break;
case InterpolationType.LINEAR:
key.inTangent = GetCurveKeyframeLeftLinearSlope(keyframes, keyframeIndex);
key.outTangent = GetCurveKeyframeLeftLinearSlope(keyframes, keyframeIndex + 1);
break;
case InterpolationType.STEP:
key.inTangent = float.PositiveInfinity;
key.outTangent = float.PositiveInfinity;
break;
default:
throw new NotImplementedException();
}
if(curve.length < keyframeIndex)
curve.MoveKey(keyframeIndex, key);
}
private static float GetCurveKeyframeLeftLinearSlope(Keyframe[] keyframes, int keyframeIndex)
{
if (keyframeIndex <= 0 || keyframeIndex >= keyframes.Length)
{
return 0;
}
var valueDelta = keyframes[keyframeIndex].value - keyframes[keyframeIndex - 1].value;
var timeDelta = keyframes[keyframeIndex].time - keyframes[keyframeIndex - 1].time;
if (timeDelta <= 0)
{
var k = keyframes[keyframeIndex];
k.time = keyframes[keyframeIndex - 1].time + Mathf.Epsilon + 1 / 100f;
keyframes[keyframeIndex] = k;
Debug.Log(LogType.Warning, "Time of subsequent animation keyframes is not increasing (glTF-Validator error ACCESSOR_ANIMATION_INPUT_NON_INCREASING)");
return float.PositiveInfinity;
}
return valueDelta / timeDelta;
}
protected async Task<AnimationClip> ConstructClip(Transform root, int animationId, CancellationToken cancellationToken)
{
GLTFAnimation animation = _gltfRoot.Animations[animationId];
AnimationCacheData animationCache = _assetCache.AnimationCache[animationId];
if (animationCache == null)
{
animationCache = new AnimationCacheData(animation.Samplers.Count);
_assetCache.AnimationCache[animationId] = animationCache;
}
else if (animationCache.LoadedAnimationClip != null)
{
return animationCache.LoadedAnimationClip;
}
// unpack accessors
await BuildAnimationSamplers(animation, animationId);
// init clip
AnimationClip clip = new AnimationClip
{
name = animation.Name ?? $"animation:{animationId}",
};
_assetCache.AnimationCache[animationId].LoadedAnimationClip = clip;
if (_options.AnimationMethod == AnimationMethod.Legacy)
clip.legacy = true;
foreach (AnimationChannel channel in animation.Channels)
{
AnimationSamplerCacheData samplerCache = animationCache.Samplers[channel.Sampler.Id];
if (channel.Target.Node == null)
{
// If a channel doesn't have a target node, then just skip it.
// This is legal and is present in one of the asset generator models, but means that animation doesn't actually do anything.
// https://github.com/KhronosGroup/glTF-Asset-Generator/tree/master/Output/Positive/Animation_NodeMisc
// Model 08
continue;
}
var node = await GetNode(channel.Target.Node.Id, cancellationToken);
string relativePath = RelativePathFrom(node.transform, root);
NumericArray input = samplerCache.Input.AccessorContent,
output = samplerCache.Output.AccessorContent;
string[] propertyNames;
var known = Enum.TryParse(channel.Target.Path, out GLTFAnimationChannelPath path);
if (!known) continue;
switch (path)
{
case GLTFAnimationChannelPath.translation:
propertyNames = new string[] { "localPosition.x", "localPosition.y", "localPosition.z" };
SetAnimationCurve(clip, relativePath, propertyNames, input, output,
samplerCache.Interpolation, typeof(Transform),
(data, frame) =>
{
var position = data.AsVec3s[frame].ToUnityVector3Convert();
return new float[] { position.x, position.y, position.z };
});
break;
case GLTFAnimationChannelPath.rotation:
propertyNames = new string[] { "localRotation.x", "localRotation.y", "localRotation.z", "localRotation.w" };
SetAnimationCurve(clip, relativePath, propertyNames, input, output,
samplerCache.Interpolation, typeof(Transform),
(data, frame) =>
{
var rotation = data.AsVec4s[frame];
var quaternion = new GLTF.Math.Quaternion(rotation.X, rotation.Y, rotation.Z, rotation.W).ToUnityQuaternionConvert();
return new float[] { quaternion.x, quaternion.y, quaternion.z, quaternion.w };
});
break;
case GLTFAnimationChannelPath.scale:
propertyNames = new string[] { "localScale.x", "localScale.y", "localScale.z" };
SetAnimationCurve(clip, relativePath, propertyNames, input, output,
samplerCache.Interpolation, typeof(Transform),
(data, frame) =>
{
var scale = data.AsVec3s[frame].ToUnityVector3Raw();
return new float[] { scale.x, scale.y, scale.z };
});
break;
case GLTFAnimationChannelPath.weights:
var primitives = channel.Target.Node.Value.Mesh.Value.Primitives;
var targetCount = primitives[0].Targets.Count;
for (int primitiveIndex = 0; primitiveIndex < primitives.Count; primitiveIndex++)
{
// see SceneImporter:156
// blend shapes are always called "Morphtarget" and always have frame weight 100 on import
var prim = primitives[primitiveIndex];
var targetNames = prim.TargetNames;
propertyNames = new string[targetCount];
for (var i = 0; i < targetCount; i++)
propertyNames[i] = "blendShape." + (targetNames != null ? targetNames[i] : ("Morphtarget" + i));
var frameFloats = new float[targetCount];
SetAnimationCurve(clip, relativePath, propertyNames, input, output,
samplerCache.Interpolation, typeof(SkinnedMeshRenderer),
(data, frame) =>
{
var allValues = data.AsFloats;
for (var k = 0; k < targetCount; k++)
frameFloats[k] = allValues[frame * targetCount + k];
return frameFloats;
});
}
break;
default:
Debug.Log(LogType.Warning, "Cannot read GLTF animation path");
break;
} // switch target type
} // foreach channel
clip.EnsureQuaternionContinuity();
return clip;
}
#endif
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 20eade7af2db4b06a0d23b23c3a83c47
timeCreated: 1657012127
@@ -0,0 +1,93 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using GLTF.Schema;
using UnityEngine;
namespace UnityGLTF
{
public partial class GLTFSceneImporter
{
private async Task ConstructLods(GLTFRoot gltfRoot, GameObject nodeObj, Node node, int nodeIndex, CancellationToken cancellationToken)
{
const string msft_LODExtName = MSFT_LODExtensionFactory.EXTENSION_NAME;
MSFT_LODExtension lodsExtension = null;
if (_gltfRoot.ExtensionsUsed != null
&& _gltfRoot.ExtensionsUsed.Contains(msft_LODExtName)
&& node.Extensions != null
&& node.Extensions.ContainsKey(msft_LODExtName))
{
lodsExtension = node.Extensions[msft_LODExtName] as MSFT_LODExtension;
if (lodsExtension != null && lodsExtension.NodeIds.Count > 0)
{
int lodCount = lodsExtension.NodeIds.Count + 1;
if (CullFarLOD)
{
lodCount += 1;
}
LOD[] lods = new LOD[lodCount];
List<double> lodCoverage = lodsExtension.GetLODCoverage(node);
if (lodCoverage == null)
lodCoverage = new List<double>();
var hasExplicitLodCoverage = lodCoverage.Count > 0;
if (lodCoverage.Count != lods.Length)
{
if (!hasExplicitLodCoverage)
lodCoverage.Add(0.5f);
var count = lodCoverage.Count;
var length = lods.Length;
for (var i = count; i < length; i++)
{
lodCoverage.Add(lodCoverage[i - 1] / 2);
}
if (!CullFarLOD && !hasExplicitLodCoverage)
lodCoverage[lodCoverage.Count - 1] = 0;
}
// sanitize values so that they are strictly decreasing
for (int i = lodCoverage.Count - 2; i >= 0; i--)
{
if (lodCoverage[i] <= lodCoverage[i + 1])
lodCoverage[i] = lodCoverage[i + 1] + 0.01f;
}
var lodGroupNodeObj = nodeObj;
lodGroupNodeObj.SetActive(false);
var firstLodChildRenderers = nodeObj.GetComponentsInChildren<Renderer>().ToList();
LODGroup lodGroup = lodGroupNodeObj.AddComponent<LODGroup>();
for (int i = 0; i < lodsExtension.NodeIds.Count; i++)
{
int lodNodeId = lodsExtension.NodeIds[i];
var lodNodeObj = await GetNode(lodNodeId, cancellationToken);
// progressStatus.NodeTotal++;
lodNodeObj.transform.SetParent(lodGroupNodeObj.transform, false);
var childRenderers = lodNodeObj.GetComponentsInChildren<Renderer>();
int lodIndex = i + 1;
// make sure to kick out the renderers that are used in lower LOD levels from the root LOD level
foreach (var child in childRenderers)
firstLodChildRenderers.Remove(child);
lods[lodIndex] = new LOD(GetLodCoverage(lodCoverage, lodIndex), childRenderers);
}
lods[0] = new LOD(GetLodCoverage(lodCoverage, 0), firstLodChildRenderers.ToArray());
if (CullFarLOD)
{
//use the last mesh as the LOD
lods[lodsExtension.NodeIds.Count + 1] = new LOD(0, null);
}
lodGroup.SetLODs(lods);
lodGroup.RecalculateBounds();
lodGroupNodeObj.SetActive(true);
_assetCache.NodeCache[nodeIndex] = lodGroupNodeObj;
}
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: fe34f290cdf64038ad7d60c706251109
timeCreated: 1675772109
@@ -0,0 +1,53 @@
using GLTF.Schema;
using GLTF.Schema.KHR_lights_punctual;
using UnityEngine;
using LightType = UnityEngine.LightType;
namespace UnityGLTF
{
public partial class GLTFSceneImporter
{
private void ConstructLights(GameObject nodeObj, Node node)
{
// TODO this should be handled by the lights extension directly, not here
const string lightExt = KHR_lights_punctualExtensionFactory.EXTENSION_NAME;
KHR_LightsPunctualNodeExtension lightsExtension = null;
if (_gltfRoot.ExtensionsUsed != null && _gltfRoot.ExtensionsUsed.Contains(lightExt) && node.Extensions != null && node.Extensions.ContainsKey(lightExt))
{
lightsExtension = node.Extensions[lightExt] as KHR_LightsPunctualNodeExtension;
var l = lightsExtension.LightId;
var light = l.Value;
var newLight = nodeObj.AddComponent<Light>();
switch (light.Type)
{
case GLTF.Schema.KHR_lights_punctual.LightType.spot:
newLight.type = LightType.Spot;
break;
case GLTF.Schema.KHR_lights_punctual.LightType.directional:
newLight.type = LightType.Directional;
break;
case GLTF.Schema.KHR_lights_punctual.LightType.point:
newLight.type = LightType.Point;
break;
}
newLight.name = light.Name;
newLight.intensity = (float) light.Intensity / Mathf.PI;
newLight.color = new Color(light.Color.R, light.Color.G, light.Color.B, light.Color.A);
newLight.range = (float) light.Range;
if (light.Spot != null)
{
#if UNITY_2019_1_OR_NEWER
newLight.innerSpotAngle = (float) light.Spot.InnerConeAngle * 2 / (Mathf.Deg2Rad * 0.8f);
#endif
newLight.spotAngle = (float) light.Spot.OuterConeAngle * 2 / Mathf.Deg2Rad;
}
// flip?
nodeObj.transform.localRotation *= Quaternion.Euler(0, 180, 0);
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7b547db626e3430c87fe1e060a131222
timeCreated: 1657014645
@@ -0,0 +1,641 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using GLTF.Schema;
using UnityEngine;
using UnityGLTF.Cache;
using UnityGLTF.Extensions;
namespace UnityGLTF
{
public partial class GLTFSceneImporter
{
protected virtual async Task ConstructMaterial(GLTFMaterial def, int materialIndex)
{
IUniformMap mapper;
const string specGlossExtName = KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME;
const string unlitExtName = KHR_MaterialsUnlitExtensionFactory.EXTENSION_NAME;
if (_gltfRoot.ExtensionsUsed != null && _gltfRoot.ExtensionsUsed.Contains(specGlossExtName) && def.Extensions != null && def.Extensions.ContainsKey(specGlossExtName))
{
if (!string.IsNullOrEmpty(CustomShaderName))
{
mapper = new SpecGlossMap(CustomShaderName, MaximumLod);
}
else
{
mapper = new SpecGlossMap(MaximumLod);
}
}
else if (_gltfRoot.ExtensionsUsed != null && _gltfRoot.ExtensionsUsed.Contains(unlitExtName) && def.Extensions != null && def.Extensions.ContainsKey(unlitExtName))
{
if (!string.IsNullOrEmpty(CustomShaderName))
{
mapper = new UnlitMap(CustomShaderName, null, MaximumLod);
}
else
{
#if UNITY_2021_3_OR_NEWER
mapper = new UnlitGraphMap();
#elif UNITY_2019_1_OR_NEWER
if (UnityEngine.Rendering.GraphicsSettings.currentRenderPipeline)
mapper = new UnlitGraphMap(def.AlphaMode == AlphaMode.BLEND, def.DoubleSided);
else
mapper = new UnlitMap(MaximumLod);
#else
mapper = new UnlitMap(MaximumLod);
#endif
}
}
else
{
if (!string.IsNullOrEmpty(CustomShaderName))
{
mapper = new MetalRoughMap(CustomShaderName, MaximumLod);
}
else
{
// do we have URP or Unity 2021.2+? Use the PBR Graph Material!
#if UNITY_2021_3_OR_NEWER
mapper = new PBRGraphMap();
#elif UNITY_2019_1_OR_NEWER
if (UnityEngine.Rendering.GraphicsSettings.currentRenderPipeline)
mapper = new PBRGraphMap(def.AlphaMode == AlphaMode.BLEND, def.DoubleSided);
else
mapper = new MetalRoughMap(MaximumLod);
#else
mapper = new MetalRoughMap(MaximumLod);
#endif
}
}
mapper.Material.name = def.Name;
mapper.AlphaMode = def.AlphaMode;
mapper.AlphaCutoff = def.AlphaCutoff;
mapper.DoubleSided = def.DoubleSided;
mapper.Material.SetFloat("_BUILTIN_QueueControl", -1);
mapper.Material.SetFloat("_QueueControl", -1);
var mrMapper = mapper as IMetalRoughUniformMap;
if (def.PbrMetallicRoughness != null && mrMapper != null)
{
var pbr = def.PbrMetallicRoughness;
mrMapper.BaseColorFactor = pbr.BaseColorFactor.ToUnityColorRaw();
if (pbr.BaseColorTexture != null)
{
TextureId textureId = pbr.BaseColorTexture.Index;
await ConstructTexture(textureId.Value, textureId.Id, !KeepCPUCopyOfTexture, false);
mrMapper.BaseColorTexture = _assetCache.TextureCache[textureId.Id].Texture;
mrMapper.BaseColorTexCoord = pbr.BaseColorTexture.TexCoord;
var ext = GetTextureTransform(pbr.BaseColorTexture);
if (ext != null)
{
var offset = ext.Offset.ToUnityVector2Raw();
offset.y = 1 - ext.Scale.Y - offset.y;
mrMapper.BaseColorXOffset = offset;
mrMapper.BaseColorXRotation = ext.Rotation;
mrMapper.BaseColorXScale = ext.Scale.ToUnityVector2Raw();
mrMapper.BaseColorXTexCoord = ext.TexCoord;
MatHelper.SetKeyword(mapper.Material, "_TEXTURE_TRANSFORM", true);
}
}
mrMapper.MetallicFactor = pbr.MetallicFactor;
mrMapper.RoughnessFactor = pbr.RoughnessFactor;
if (pbr.MetallicRoughnessTexture != null)
{
TextureId textureId = pbr.MetallicRoughnessTexture.Index;
await ConstructTexture(textureId.Value, textureId.Id, !KeepCPUCopyOfTexture, true);
mrMapper.MetallicRoughnessTexture = _assetCache.TextureCache[textureId.Id].Texture;
mrMapper.MetallicRoughnessTexCoord = pbr.MetallicRoughnessTexture.TexCoord;
var ext = GetTextureTransform(pbr.MetallicRoughnessTexture);
if (ext != null)
{
var offset = ext.Offset.ToUnityVector2Raw();
offset.y = 1 - ext.Scale.Y - offset.y;
mrMapper.MetallicRoughnessXOffset = offset;
mrMapper.MetallicRoughnessXRotation = ext.Rotation;
mrMapper.MetallicRoughnessXScale = ext.Scale.ToUnityVector2Raw();
mrMapper.MetallicRoughnessXTexCoord = ext.TexCoord;
}
}
}
// when PbrMetallicRoughness is not defined, default values MUST apply
else if (def.PbrMetallicRoughness == null && mrMapper != null)
{
mrMapper.MetallicFactor = 1;
mrMapper.RoughnessFactor = 1;
}
var sgMapper = mapper as ISpecGlossUniformMap;
if (sgMapper != null)
{
var specGloss = def.Extensions[specGlossExtName] as KHR_materials_pbrSpecularGlossinessExtension;
sgMapper.DiffuseFactor = specGloss.DiffuseFactor.ToUnityColorRaw();
if (specGloss.DiffuseTexture != null)
{
TextureId textureId = specGloss.DiffuseTexture.Index;
await ConstructTexture(textureId.Value, textureId.Id, !KeepCPUCopyOfTexture, false);
sgMapper.DiffuseTexture = _assetCache.TextureCache[textureId.Id].Texture;
sgMapper.DiffuseTexCoord = specGloss.DiffuseTexture.TexCoord;
var ext = GetTextureTransform(specGloss.DiffuseTexture);
if (ext != null)
{
var offset = ext.Offset.ToUnityVector2Raw();
offset.y = 1 - ext.Scale.Y - offset.y;
sgMapper.DiffuseXOffset = offset;
sgMapper.DiffuseXRotation = ext.Rotation;
sgMapper.DiffuseXScale = ext.Scale.ToUnityVector2Raw();
sgMapper.DiffuseXTexCoord = ext.TexCoord;
}
}
sgMapper.SpecularFactor = specGloss.SpecularFactor.ToUnityVector3Raw();
sgMapper.GlossinessFactor = specGloss.GlossinessFactor;
if (specGloss.SpecularGlossinessTexture != null)
{
TextureId textureId = specGloss.SpecularGlossinessTexture.Index;
await ConstructTexture(textureId.Value, textureId.Id, !KeepCPUCopyOfTexture, false);
sgMapper.SpecularGlossinessTexture = _assetCache.TextureCache[textureId.Id].Texture;
var ext = GetTextureTransform(specGloss.SpecularGlossinessTexture);
if (ext != null)
{
var offset = ext.Offset.ToUnityVector2Raw();
offset.y = 1 - ext.Scale.Y - offset.y;
sgMapper.SpecularGlossinessXOffset = offset;
sgMapper.SpecularGlossinessXRotation = ext.Rotation;
sgMapper.SpecularGlossinessXScale = ext.Scale.ToUnityVector2Raw();
sgMapper.SpecularGlossinessXTexCoord = ext.TexCoord;
}
}
}
var unlitMapper = mapper as IUnlitUniformMap;
if (unlitMapper != null)
{
var pbr = def.PbrMetallicRoughness;
unlitMapper.BaseColorFactor = pbr.BaseColorFactor.ToUnityColorRaw();
if (pbr.BaseColorTexture != null)
{
TextureId textureId = pbr.BaseColorTexture.Index;
await ConstructTexture(textureId.Value, textureId.Id, !KeepCPUCopyOfTexture, false);
unlitMapper.BaseColorTexture = _assetCache.TextureCache[textureId.Id].Texture;
unlitMapper.BaseColorTexCoord = pbr.BaseColorTexture.TexCoord;
var ext = GetTextureTransform(pbr.BaseColorTexture);
if (ext != null)
{
var offset = ext.Offset.ToUnityVector2Raw();
offset.y = 1 - ext.Scale.Y - offset.y;
unlitMapper.BaseColorXOffset = offset;
unlitMapper.BaseColorXRotation = ext.Rotation;
unlitMapper.BaseColorXScale = ext.Scale.ToUnityVector2Raw();
unlitMapper.BaseColorXTexCoord = ext.TexCoord;
unlitMapper.Material.SetKeyword("_TEXTURE_TRANSFORM", true);
}
}
}
var iorMapper = mapper as IIORMap;
if (iorMapper != null)
{
var ior = GetIOR(def);
if (ior != null)
{
iorMapper.IOR = ior.ior;
}
}
var transmissionMapper = mapper as ITransmissionMap;
if (transmissionMapper != null)
{
var transmission = GetTransmission(def);
if (transmission != null)
{
transmissionMapper.TransmissionFactor = transmission.transmissionFactor;
var td = await FromTextureInfo(transmission.transmissionTexture);
transmissionMapper.TransmissionTexture = td.Texture;
mapper.Material.renderQueue = 3000;
mapper.Material.SetKeyword("_VOLUME_TRANSMISSION", true);
mapper.Material.SetFloat("_VOLUME_TRANSMISSION_ON", 1f);
}
}
var volumeMapper = mapper as IVolumeMap;
if (volumeMapper != null)
{
var volume = GetVolume(def);
if (volume != null)
{
volumeMapper.AttenuationColor = QualitySettings.activeColorSpace == ColorSpace.Linear ? volume.attenuationColor.ToUnityColorLinear() : volume.attenuationColor.ToUnityColorRaw();
volumeMapper.AttenuationDistance = volume.attenuationDistance;
volumeMapper.ThicknessFactor = volume.thicknessFactor;
var td = await FromTextureInfo(volume.thicknessTexture);
volumeMapper.ThicknessTexture = td.Texture;
mapper.Material.renderQueue = 3000;
mapper.Material.SetFloat("_VOLUME_ON", 1f);
}
}
var iridescenceMapper = mapper as IIridescenceMap;
if (iridescenceMapper != null)
{
var iridescence = GetIridescence(def);
if (iridescence != null)
{
iridescenceMapper.IridescenceFactor = iridescence.iridescenceFactor;
iridescenceMapper.IridescenceIor = iridescence.iridescenceIor;
iridescenceMapper.IridescenceThicknessMinimum = iridescence.iridescenceThicknessMinimum;
iridescenceMapper.IridescenceThicknessMaximum = iridescence.iridescenceThicknessMaximum;
var td = await FromTextureInfo(iridescence.iridescenceTexture);
iridescenceMapper.IridescenceTexture = td.Texture;
var td2 = await FromTextureInfo(iridescence.iridescenceThicknessTexture);
iridescenceMapper.IridescenceThicknessTexture = td2.Texture;
mapper.Material.SetKeyword("_IRIDESCENCE", true);
}
}
var specularMapper = mapper as ISpecularMap;
if (specularMapper != null)
{
var specular = GetSpecular(def);
if (specular != null)
{
specularMapper.SpecularFactor = specular.specularFactor;
specularMapper.SpecularColorFactor = specular.specularColorFactor.ToUnityColorLinear();
var td = await FromTextureInfo(specular.specularTexture);
specularMapper.SpecularTexture = td.Texture;
var td2 = await FromTextureInfo(specular.specularColorTexture);
specularMapper.SpecularColorTexture = td2.Texture;
mapper.Material.SetKeyword("_SPECULAR", true);
}
}
var clearcoatMapper = mapper as IClearcoatMap;
if (clearcoatMapper != null)
{
var clearcoat = GetClearcoat(def);
if (clearcoat != null)
{
clearcoatMapper.ClearcoatFactor = clearcoat.clearcoatFactor;
clearcoatMapper.ClearcoatRoughnessFactor = clearcoat.clearcoatRoughnessFactor;
var td = await FromTextureInfo(clearcoat.clearcoatTexture);
clearcoatMapper.ClearcoatTexture = td.Texture;
var td2 = await FromTextureInfo(clearcoat.clearcoatRoughnessTexture);
clearcoatMapper.ClearcoatRoughnessTexture = td2.Texture;
var td3 = await FromTextureInfo(clearcoat.clearcoatNormalTexture);
clearcoatMapper.ClearcoatNormalTexture = td3.Texture;
mapper.Material.SetKeyword("_CLEARCOAT", true);
}
}
var uniformMapper = mapper as ILitMap;
if (uniformMapper != null)
{
if (def.NormalTexture != null)
{
TextureId textureId = def.NormalTexture.Index;
await ConstructTexture(textureId.Value, textureId.Id, !KeepCPUCopyOfTexture, true);
uniformMapper.NormalTexture = _assetCache.TextureCache[textureId.Id].Texture;
uniformMapper.NormalTexCoord = def.NormalTexture.TexCoord;
uniformMapper.NormalTexScale = def.NormalTexture.Scale;
var ext = GetTextureTransform(def.NormalTexture);
if (ext != null)
{
var offset = ext.Offset.ToUnityVector2Raw();
offset.y = 1 - ext.Scale.Y - offset.y;
uniformMapper.NormalXOffset = offset;
uniformMapper.NormalXRotation = ext.Rotation;
uniformMapper.NormalXScale = ext.Scale.ToUnityVector2Raw();
uniformMapper.NormalXTexCoord = ext.TexCoord;
mapper.Material.SetKeyword("_TEXTURE_TRANSFORM", true);
// workaround for PBRGraph not supporting per-texture transforms right now
if (mapper is IMetalRoughUniformMap map && !map.BaseColorTexture)
{
map.BaseColorXScale = ext.Scale.ToUnityVector2Raw();
map.BaseColorXOffset = offset;
}
}
}
if (def.EmissiveTexture != null)
{
TextureId textureId = def.EmissiveTexture.Index;
await ConstructTexture(textureId.Value, textureId.Id, !KeepCPUCopyOfTexture, false);
uniformMapper.EmissiveTexture = _assetCache.TextureCache[textureId.Id].Texture;
uniformMapper.EmissiveTexCoord = def.EmissiveTexture.TexCoord;
var ext = GetTextureTransform(def.EmissiveTexture);
if (ext != null)
{
var offset = ext.Offset.ToUnityVector2Raw();
offset.y = 1 - ext.Scale.Y - offset.y;
uniformMapper.EmissiveXOffset = offset;
uniformMapper.EmissiveXRotation = ext.Rotation;
uniformMapper.EmissiveXScale = ext.Scale.ToUnityVector2Raw();
uniformMapper.EmissiveXTexCoord = ext.TexCoord;
mapper.Material.SetKeyword("_TEXTURE_TRANSFORM", true);
// workaround for PBRGraph not supporting per-texture transforms right now
if (mapper is IMetalRoughUniformMap map && !map.BaseColorTexture && !map.NormalTexture)
{
map.BaseColorXScale = ext.Scale.ToUnityVector2Raw();
map.BaseColorXOffset = offset;
}
}
}
if (def.OcclusionTexture != null)
{
uniformMapper.OcclusionTexStrength = def.OcclusionTexture.Strength;
TextureId textureId = def.OcclusionTexture.Index;
await ConstructTexture(textureId.Value, textureId.Id, !KeepCPUCopyOfTexture, true);
uniformMapper.OcclusionTexture = _assetCache.TextureCache[textureId.Id].Texture;
uniformMapper.OcclusionTexCoord = def.OcclusionTexture.TexCoord;
var ext = GetTextureTransform(def.OcclusionTexture);
if (ext != null)
{
var offset = ext.Offset.ToUnityVector2Raw();
offset.y = 1 - ext.Scale.Y - offset.y;
uniformMapper.OcclusionXOffset = offset;
uniformMapper.OcclusionXRotation = ext.Rotation;
uniformMapper.OcclusionXScale = ext.Scale.ToUnityVector2Raw();
// mapper.OcclusionXTexCoord = ext.TexCoord;
mapper.Material.SetKeyword("_TEXTURE_TRANSFORM", true);
// workaround for PBRGraph not supporting per-texture transforms right now
if (mapper is IMetalRoughUniformMap map && !map.BaseColorTexture && !map.NormalTexture && !map.EmissiveTexture)
{
map.BaseColorXScale = ext.Scale.ToUnityVector2Raw();
map.BaseColorXOffset = offset;
}
}
}
uniformMapper.EmissiveFactor = QualitySettings.activeColorSpace == ColorSpace.Linear ? def.EmissiveFactor.ToUnityColorLinear() : def.EmissiveFactor.ToUnityColorRaw();
var emissiveExt = GetEmissiveStrength(def);
if (emissiveExt != null)
{
uniformMapper.EmissiveFactor = uniformMapper.EmissiveFactor * emissiveExt.emissiveStrength;
}
}
var vertColorMapper = mapper.Clone();
vertColorMapper.VertexColorsEnabled = true;
// if (mapper is PBRGraphMap pbrGraphMap)
// {
// MaterialExtensions.ValidateMaterialKeywords(pbrGraphMap.Material);
// }
MaterialCacheData materialWrapper = new MaterialCacheData
{
UnityMaterial = mapper.Material,
UnityMaterialWithVertexColor = vertColorMapper.Material,
GLTFMaterial = def
};
if (materialIndex >= 0)
{
_assetCache.MaterialCache[materialIndex] = materialWrapper;
}
else
{
_defaultLoadedMaterial = materialWrapper;
}
}
protected virtual Task ConstructMaterialImageBuffers(GLTFMaterial def)
{
var tasks = new List<Task>(8);
if (def.PbrMetallicRoughness != null)
{
var pbr = def.PbrMetallicRoughness;
if (pbr.BaseColorTexture != null)
{
var textureId = pbr.BaseColorTexture.Index;
tasks.Add(ConstructImageBuffer(textureId.Value, textureId.Id));
}
if (pbr.MetallicRoughnessTexture != null)
{
var textureId = pbr.MetallicRoughnessTexture.Index;
tasks.Add(ConstructImageBuffer(textureId.Value, textureId.Id));
}
}
if (def.CommonConstant != null)
{
if (def.CommonConstant.LightmapTexture != null)
{
var textureId = def.CommonConstant.LightmapTexture.Index;
tasks.Add(ConstructImageBuffer(textureId.Value, textureId.Id));
}
}
if (def.NormalTexture != null)
{
var textureId = def.NormalTexture.Index;
tasks.Add(ConstructImageBuffer(textureId.Value, textureId.Id));
}
if (def.OcclusionTexture != null)
{
var textureId = def.OcclusionTexture.Index;
if (!(def.PbrMetallicRoughness != null
&& def.PbrMetallicRoughness.MetallicRoughnessTexture != null
&& def.PbrMetallicRoughness.MetallicRoughnessTexture.Index.Id == textureId.Id))
{
tasks.Add(ConstructImageBuffer(textureId.Value, textureId.Id));
}
}
if (def.EmissiveTexture != null)
{
var textureId = def.EmissiveTexture.Index;
tasks.Add(ConstructImageBuffer(textureId.Value, textureId.Id));
}
// pbr_spec_gloss extension
const string specGlossExtName = KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME;
if (def.Extensions != null && def.Extensions.ContainsKey(specGlossExtName))
{
var specGlossDef = (KHR_materials_pbrSpecularGlossinessExtension)def.Extensions[specGlossExtName];
if (specGlossDef.DiffuseTexture != null)
{
var textureId = specGlossDef.DiffuseTexture.Index;
tasks.Add(ConstructImageBuffer(textureId.Value, textureId.Id));
}
if (specGlossDef.SpecularGlossinessTexture != null)
{
var textureId = specGlossDef.SpecularGlossinessTexture.Index;
tasks.Add(ConstructImageBuffer(textureId.Value, textureId.Id));
}
}
if (def.Extensions != null && def.Extensions.ContainsKey(KHR_materials_transmission_Factory.EXTENSION_NAME))
{
var transmissionDef = (KHR_materials_transmission)def.Extensions[KHR_materials_transmission_Factory.EXTENSION_NAME];
if (transmissionDef.transmissionTexture != null)
{
var textureId = transmissionDef.transmissionTexture.Index;
tasks.Add(ConstructImageBuffer(textureId.Value, textureId.Id));
}
}
if (def.Extensions != null && def.Extensions.ContainsKey(KHR_materials_volume_Factory.EXTENSION_NAME))
{
var transmissionDef = (KHR_materials_volume)def.Extensions[KHR_materials_volume_Factory.EXTENSION_NAME];
if (transmissionDef.thicknessTexture != null)
{
var textureId = transmissionDef.thicknessTexture.Index;
tasks.Add(ConstructImageBuffer(textureId.Value, textureId.Id));
}
}
if (def.Extensions != null && def.Extensions.ContainsKey(KHR_materials_iridescence_Factory.EXTENSION_NAME))
{
var iridescenceDef = (KHR_materials_iridescence) def.Extensions[KHR_materials_iridescence_Factory.EXTENSION_NAME];
if (iridescenceDef.iridescenceTexture != null)
{
var textureId = iridescenceDef.iridescenceTexture.Index;
tasks.Add(ConstructImageBuffer(textureId.Value, textureId.Id));
}
if (iridescenceDef.iridescenceThicknessTexture != null)
{
var textureId = iridescenceDef.iridescenceThicknessTexture.Index;
tasks.Add(ConstructImageBuffer(textureId.Value, textureId.Id));
}
}
if (def.Extensions != null && def.Extensions.ContainsKey(KHR_materials_specular_Factory.EXTENSION_NAME))
{
var specularDef = (KHR_materials_specular) def.Extensions[KHR_materials_specular_Factory.EXTENSION_NAME];
if (specularDef.specularTexture != null)
{
var textureId = specularDef.specularTexture.Index;
tasks.Add(ConstructImageBuffer(textureId.Value, textureId.Id));
}
if (specularDef.specularColorTexture != null)
{
var textureId = specularDef.specularColorTexture.Index;
tasks.Add(ConstructImageBuffer(textureId.Value, textureId.Id));
}
}
return Task.WhenAll(tasks);
}
protected virtual ExtTextureTransformExtension GetTextureTransform(TextureInfo def)
{
IExtension extension;
if (_gltfRoot.ExtensionsUsed != null &&
_gltfRoot.ExtensionsUsed.Contains(ExtTextureTransformExtensionFactory.EXTENSION_NAME) &&
def.Extensions != null &&
def.Extensions.TryGetValue(ExtTextureTransformExtensionFactory.EXTENSION_NAME, out extension))
{
return (ExtTextureTransformExtension)extension;
}
else return null;
}
protected virtual KHR_materials_emissive_strength GetEmissiveStrength(GLTFMaterial def)
{
if (_gltfRoot.ExtensionsUsed != null && _gltfRoot.ExtensionsUsed.Contains(KHR_materials_emissive_strength_Factory.EXTENSION_NAME) &&
def.Extensions != null && def.Extensions.TryGetValue(KHR_materials_emissive_strength_Factory.EXTENSION_NAME, out var extension))
{
return (KHR_materials_emissive_strength) extension;
}
else return null;
}
protected virtual KHR_materials_transmission GetTransmission(GLTFMaterial def)
{
if (_gltfRoot.ExtensionsUsed != null && _gltfRoot.ExtensionsUsed.Contains(KHR_materials_transmission_Factory.EXTENSION_NAME) &&
def.Extensions != null && def.Extensions.TryGetValue(KHR_materials_transmission_Factory.EXTENSION_NAME, out var extension))
{
return (KHR_materials_transmission) extension;
}
return null;
}
protected virtual KHR_materials_volume GetVolume(GLTFMaterial def)
{
if (_gltfRoot.ExtensionsUsed != null && _gltfRoot.ExtensionsUsed.Contains(KHR_materials_volume_Factory.EXTENSION_NAME) &&
def.Extensions != null && def.Extensions.TryGetValue(KHR_materials_volume_Factory.EXTENSION_NAME, out var extension))
{
return (KHR_materials_volume) extension;
}
return null;
}
protected virtual KHR_materials_ior GetIOR(GLTFMaterial def)
{
if (_gltfRoot.ExtensionsUsed != null && _gltfRoot.ExtensionsUsed.Contains(KHR_materials_ior_Factory.EXTENSION_NAME) &&
def.Extensions != null && def.Extensions.TryGetValue(KHR_materials_ior_Factory.EXTENSION_NAME, out var extension))
{
return (KHR_materials_ior) extension;
}
return null;
}
protected virtual KHR_materials_iridescence GetIridescence(GLTFMaterial def)
{
if (_gltfRoot.ExtensionsUsed != null && _gltfRoot.ExtensionsUsed.Contains(KHR_materials_iridescence_Factory.EXTENSION_NAME) &&
def.Extensions != null && def.Extensions.TryGetValue(KHR_materials_iridescence_Factory.EXTENSION_NAME, out var extension))
{
return (KHR_materials_iridescence) extension;
}
return null;
}
protected virtual KHR_materials_specular GetSpecular(GLTFMaterial def)
{
if (_gltfRoot.ExtensionsUsed != null && _gltfRoot.ExtensionsUsed.Contains(KHR_materials_specular_Factory.EXTENSION_NAME) &&
def.Extensions != null && def.Extensions.TryGetValue(KHR_materials_specular_Factory.EXTENSION_NAME, out var extension))
{
return (KHR_materials_specular) extension;
}
return null;
}
protected virtual KHR_materials_clearcoat GetClearcoat(GLTFMaterial def)
{
if (_gltfRoot.ExtensionsUsed != null && _gltfRoot.ExtensionsUsed.Contains(KHR_materials_clearcoat_Factory.EXTENSION_NAME) &&
def.Extensions != null && def.Extensions.TryGetValue(KHR_materials_clearcoat_Factory.EXTENSION_NAME, out var extension))
{
return (KHR_materials_clearcoat) extension;
}
return null;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 25e2614154434641a15540a7203e47f6
timeCreated: 1657012132
@@ -0,0 +1,573 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using GLTF;
using GLTF.Schema;
using UnityEngine;
using UnityEngine.Rendering;
using UnityGLTF.Cache;
using UnityGLTF.Extensions;
namespace UnityGLTF
{
public partial class GLTFSceneImporter
{
/// <summary>
/// Triggers loading, converting, and constructing of a UnityEngine.Mesh, and stores it in the asset cache
/// </summary>
/// <param name="mesh">The definition of the mesh to generate</param>
/// <param name="meshIndex">The index of the mesh to generate</param>
/// <param name="cancellationToken"></param>
/// <returns>A task that completes when the mesh is attached to the given GameObject</returns>
protected virtual async Task ConstructMesh(GLTFMesh mesh, int meshIndex, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (_assetCache.MeshCache[meshIndex] == null)
{
throw new Exception("Cannot generate mesh before ConstructMeshAttributes is called!");
}
else if (_assetCache.MeshCache[meshIndex].LoadedMesh)
{
return;
}
var totalVertCount = mesh.Primitives.Aggregate((uint)0, (sum, p) => sum + p.Attributes[SemanticProperties.POSITION].Value.Count);
var vertOffset = 0;
var firstPrim = mesh.Primitives[0];
var meshCache = _assetCache.MeshCache[meshIndex];
UnityMeshData unityData = new UnityMeshData()
{
Vertices = new Vector3[totalVertCount],
Normals = firstPrim.Attributes.ContainsKey(SemanticProperties.NORMAL) ? new Vector3[totalVertCount] : null,
Tangents = firstPrim.Attributes.ContainsKey(SemanticProperties.TANGENT) ? new Vector4[totalVertCount] : null,
Uv1 = firstPrim.Attributes.ContainsKey(SemanticProperties.TEXCOORD_0) ? new Vector2[totalVertCount] : null,
Uv2 = firstPrim.Attributes.ContainsKey(SemanticProperties.TEXCOORD_1) ? new Vector2[totalVertCount] : null,
Uv3 = firstPrim.Attributes.ContainsKey(SemanticProperties.TEXCOORD_2) ? new Vector2[totalVertCount] : null,
Uv4 = firstPrim.Attributes.ContainsKey(SemanticProperties.TEXCOORD_3) ? new Vector2[totalVertCount] : null,
Colors = firstPrim.Attributes.ContainsKey(SemanticProperties.COLOR_0) ? new Color[totalVertCount] : null,
BoneWeights = firstPrim.Attributes.ContainsKey(SemanticProperties.WEIGHTS_0) ? new BoneWeight[totalVertCount] : null,
MorphTargetVertices = firstPrim.Targets != null && firstPrim.Targets[0].ContainsKey(SemanticProperties.POSITION) ?
Allocate2dArray<Vector3>((uint)firstPrim.Targets.Count, totalVertCount) : null,
MorphTargetNormals = firstPrim.Targets != null && firstPrim.Targets[0].ContainsKey(SemanticProperties.NORMAL) ?
Allocate2dArray<Vector3>((uint)firstPrim.Targets.Count, totalVertCount) : null,
MorphTargetTangents = firstPrim.Targets != null && firstPrim.Targets[0].ContainsKey(SemanticProperties.TANGENT) ?
Allocate2dArray<Vector3>((uint)firstPrim.Targets.Count, totalVertCount) : null,
Topology = new MeshTopology[mesh.Primitives.Count],
Indices = new int[mesh.Primitives.Count][]
};
for (int i = 0; i < mesh.Primitives.Count; ++i)
{
var primitive = mesh.Primitives[i];
var primCache = meshCache.Primitives[i];
unityData.Topology[i] = GetTopology(primitive.Mode);
if (IsMultithreaded)
{
await Task.Run(() => ConvertAttributeAccessorsToUnityTypes(primCache, unityData, vertOffset, i));
}
else
{
ConvertAttributeAccessorsToUnityTypes(primCache, unityData, vertOffset, i);
}
bool shouldUseDefaultMaterial = primitive.Material == null;
GLTFMaterial materialToLoad = shouldUseDefaultMaterial ? DefaultMaterial : primitive.Material.Value;
if ((shouldUseDefaultMaterial && _defaultLoadedMaterial == null) ||
(!shouldUseDefaultMaterial && _assetCache.MaterialCache[primitive.Material.Id] == null))
{
await ConstructMaterial(materialToLoad, shouldUseDefaultMaterial ? -1 : primitive.Material.Id);
}
cancellationToken.ThrowIfCancellationRequested();
var vertCount = primitive.Attributes[SemanticProperties.POSITION].Value.Count;
vertOffset += (int)vertCount;
if (unityData.Topology[i] == MeshTopology.Triangles && primitive.Indices != null && primitive.Indices.Value != null)
{
Statistics.TriangleCount += primitive.Indices.Value.Count / 3;
}
}
Statistics.VertexCount += vertOffset;
await ConstructUnityMesh(unityData, meshIndex, mesh.Name);
}
/// <summary>
/// Populate a UnityEngine.Mesh from preloaded and preprocessed buffer data
/// </summary>
/// <param name="meshConstructionData"></param>
/// <param name="meshId"></param>
/// <param name="primitiveIndex"></param>
/// <param name="unityMeshData"></param>
/// <returns></returns>
protected async Task ConstructUnityMesh(UnityMeshData unityMeshData, int meshIndex, string meshName)
{
await YieldOnTimeoutAndThrowOnLowMemory();
Mesh mesh = new Mesh
{
name = meshName,
#if UNITY_2017_3_OR_NEWER
indexFormat = unityMeshData.Vertices.Length > 65535 ? IndexFormat.UInt32 : IndexFormat.UInt16,
#endif
};
mesh.vertices = unityMeshData.Vertices;
await YieldOnTimeoutAndThrowOnLowMemory();
mesh.normals = unityMeshData.Normals;
await YieldOnTimeoutAndThrowOnLowMemory();
mesh.tangents = unityMeshData.Tangents;
await YieldOnTimeoutAndThrowOnLowMemory();
mesh.uv = unityMeshData.Uv1;
await YieldOnTimeoutAndThrowOnLowMemory();
mesh.uv2 = unityMeshData.Uv2;
await YieldOnTimeoutAndThrowOnLowMemory();
mesh.uv3 = unityMeshData.Uv3;
await YieldOnTimeoutAndThrowOnLowMemory();
mesh.uv4 = unityMeshData.Uv4;
await YieldOnTimeoutAndThrowOnLowMemory();
mesh.colors = unityMeshData.Colors;
await YieldOnTimeoutAndThrowOnLowMemory();
mesh.boneWeights = unityMeshData.BoneWeights;
await YieldOnTimeoutAndThrowOnLowMemory();
mesh.subMeshCount = unityMeshData.Indices.Length;
uint baseVertex = 0;
for (int i = 0; i < unityMeshData.Indices.Length; i++)
{
mesh.SetIndices(unityMeshData.Indices[i], unityMeshData.Topology[i], i, false, (int)baseVertex);
baseVertex += _assetCache.MeshCache[meshIndex].Primitives[i].Attributes[SemanticProperties.POSITION].AccessorId.Value.Count;
}
mesh.RecalculateBounds();
await YieldOnTimeoutAndThrowOnLowMemory();
if (unityMeshData.MorphTargetVertices != null)
{
var firstPrim = _gltfRoot.Meshes[meshIndex].Primitives[0];
for (int i = 0; i < firstPrim.Targets.Count; i++)
{
var targetName = firstPrim.TargetNames != null ? firstPrim.TargetNames[i] : $"Morphtarget{i}";
mesh.AddBlendShapeFrame(targetName, 1f,
unityMeshData.MorphTargetVertices[i],
unityMeshData.MorphTargetNormals != null ? unityMeshData.MorphTargetNormals[i] : null,
unityMeshData.MorphTargetTangents != null ? unityMeshData.MorphTargetTangents[i] : null
);
}
}
await YieldOnTimeoutAndThrowOnLowMemory();
if (unityMeshData.Normals == null && unityMeshData.Topology[0] == MeshTopology.Triangles)
{
mesh.RecalculateNormals();
}
if (!KeepCPUCopyOfMesh)
{
mesh.UploadMeshData(true);
}
_assetCache.MeshCache[meshIndex].LoadedMesh = mesh;
}
protected virtual async Task ConstructMeshTargets(MeshPrimitive primitive, int meshIndex, int primitiveIndex)
{
var newTargets = new List<Dictionary<string, AttributeAccessor>>(primitive.Targets.Count);
_assetCache.MeshCache[meshIndex].Primitives[primitiveIndex].Targets = newTargets;
for (int i = 0; i < primitive.Targets.Count; i++)
{
var target = primitive.Targets[i];
newTargets.Add(new Dictionary<string, AttributeAccessor>());
NumericArray[] sparseNormals = null;
NumericArray[] sparsePositions = null;
NumericArray[] sparseTangents = null;
const string NormalKey = "NORMALS";
const string PositionKey = "POSITIONS";
const string TangentKey = "TANGENTS";
// normals, positions, tangents
foreach (var targetAttribute in target)
{
BufferId bufferIdPair = null;
if (targetAttribute.Value.Value.Sparse == null)
{
bufferIdPair = targetAttribute.Value.Value.BufferView.Value.Buffer;
}
else
{
bufferIdPair = primitive.Attributes[targetAttribute.Key].Value.BufferView.Value.Buffer;
targetAttribute.Value.Value.BufferView = primitive.Attributes[targetAttribute.Key].Value.BufferView;
}
GLTFBuffer buffer = bufferIdPair.Value;
int bufferID = bufferIdPair.Id;
if (_assetCache.BufferCache[bufferID] == null)
{
await ConstructBuffer(buffer, bufferID);
}
newTargets[i][targetAttribute.Key] = new AttributeAccessor
{
AccessorId = targetAttribute.Value,
Stream = _assetCache.BufferCache[bufferID].Stream,
Offset = (uint)_assetCache.BufferCache[bufferID].ChunkOffset
};
// if this buffer isn't sparse, we're done here
if (targetAttribute.Value.Value.Sparse == null) continue;
// Values
var bufferId = targetAttribute.Value.Value.Sparse.Values.BufferView.Value.Buffer;
var bufferData = await GetBufferData(bufferId);
AttributeAccessor sparseValues = new AttributeAccessor
{
AccessorId = targetAttribute.Value,
Stream = bufferData.Stream,
Offset = (uint)bufferData.ChunkOffset
};
uint offset1 = GLTFHelpers.LoadBufferView(sparseValues.AccessorId.Value.Sparse.Values.BufferView.Value, sparseValues.Offset, sparseValues.Stream, out byte[] bufferViewCache1);
// Indices
bufferId = targetAttribute.Value.Value.Sparse.Indices.BufferView.Value.Buffer;
bufferData = await GetBufferData(bufferId);
AttributeAccessor sparseIndices = new AttributeAccessor
{
AccessorId = targetAttribute.Value,
Stream = bufferData.Stream,
Offset = (uint)bufferData.ChunkOffset
};
uint offset2 = GLTFHelpers.LoadBufferView(sparseIndices.AccessorId.Value.Sparse.Indices.BufferView.Value, sparseIndices.Offset, sparseIndices.Stream, out byte[] bufferViewCache2);
switch (targetAttribute.Key)
{
case NormalKey:
sparseNormals = new NumericArray[2];
Accessor.AsSparseVector3Array(targetAttribute.Value.Value, ref sparseNormals[0], bufferViewCache1, offset1);
Accessor.AsSparseUIntArray(targetAttribute.Value.Value, ref sparseNormals[1], bufferViewCache2, offset2);
break;
case PositionKey:
sparsePositions = new NumericArray[2];
Accessor.AsSparseVector3Array(targetAttribute.Value.Value, ref sparsePositions[0], bufferViewCache1, offset1);
Accessor.AsSparseUIntArray(targetAttribute.Value.Value, ref sparsePositions[1], bufferViewCache2, offset2);
break;
case TangentKey:
sparseTangents = new NumericArray[2];
Accessor.AsSparseVector3Array(targetAttribute.Value.Value, ref sparseTangents[0], bufferViewCache1, offset1);
Accessor.AsSparseUIntArray(targetAttribute.Value.Value, ref sparseTangents[1], bufferViewCache2, offset2);
break;
}
}
var att = newTargets[i];
GLTFHelpers.BuildTargetAttributes(ref att);
if (sparseNormals != null)
{
var current = att[NormalKey].AccessorContent;
NumericArray before = new NumericArray();
before.AsVec3s = new GLTF.Math.Vector3[current.AsVec3s.Length];
Array.Copy(current.AsVec3s, before.AsVec3s, before.AsVec3s.Length);
for (int j = 0; j < sparseNormals[1].AsUInts.Length; j++)
{
before.AsVec3s[sparseNormals[1].AsUInts[j]] = sparseNormals[0].AsVec3s[j];
}
att[NormalKey].AccessorContent = before;
}
if (sparsePositions != null)
{
var current = att[PositionKey].AccessorContent;
NumericArray before = new NumericArray();
before.AsVec3s = new GLTF.Math.Vector3[current.AsVec3s.Length];
Array.Copy(current.AsVec3s, before.AsVec3s, before.AsVec3s.Length);
for (int j = 0; j < sparsePositions[1].AsUInts.Length; j++)
{
before.AsVec3s[sparsePositions[1].AsUInts[j]] = sparsePositions[0].AsVec3s[j];
}
att[PositionKey].AccessorContent = before;
}
if (sparseTangents != null)
{
var current = att[TangentKey].AccessorContent;
NumericArray before = new NumericArray();
before.AsVec3s = new GLTF.Math.Vector3[current.AsVec3s.Length];
Array.Copy(current.AsVec3s, before.AsVec3s, before.AsVec3s.Length);
for (int j = 0; j < sparseTangents[1].AsUInts.Length; j++)
{
before.AsVec3s[sparseTangents[1].AsUInts[j]] = sparseTangents[0].AsVec3s[j];
}
att[TangentKey].AccessorContent = before;
}
TransformTargets(ref att);
}
}
private async Task ConstructMeshAttributes(GLTFMesh mesh, MeshId meshId)
{
int meshIndex = meshId.Id;
if (_assetCache.MeshCache[meshIndex] == null)
_assetCache.MeshCache[meshIndex] = new MeshCacheData();
else if (_assetCache.MeshCache[meshIndex].Primitives.Count > 0)
return;
for (int i = 0; i < mesh.Primitives.Count; ++i)
{
MeshPrimitive primitive = mesh.Primitives[i];
await ConstructPrimitiveAttributes(primitive, meshIndex, i);
if (primitive.Material != null)
{
await ConstructMaterialImageBuffers(primitive.Material.Value);
}
if (primitive.Targets != null)
{
// read mesh primitive targets into assetcache
await ConstructMeshTargets(primitive, meshIndex, i);
}
}
}
protected virtual async Task ConstructPrimitiveAttributes(MeshPrimitive primitive, int meshIndex, int primitiveIndex)
{
var primData = new MeshCacheData.PrimitiveCacheData();
_assetCache.MeshCache[meshIndex].Primitives.Add(primData);
var attributeAccessors = primData.Attributes;
var sparseAccessors = new Dictionary<string, (AttributeAccessor sparseIndices, AttributeAccessor sparseValues)>();
foreach (var attributePair in primitive.Attributes)
{
var bufferId = attributePair.Value.Value.BufferView.Value.Buffer;
var bufferData = await GetBufferData(bufferId);
attributeAccessors[attributePair.Key] = new AttributeAccessor
{
AccessorId = attributePair.Value,
Stream = bufferData.Stream,
Offset = (uint)bufferData.ChunkOffset
};
var sparse = attributePair.Value.Value.Sparse;
if (sparse != null)
{
var sparseBufferId = sparse.Values.BufferView.Value.Buffer;
var sparseBufferData = await GetBufferData(sparseBufferId);
AttributeAccessor sparseValues = new AttributeAccessor
{
AccessorId = attributePair.Value,
Stream = sparseBufferData.Stream,
Offset = (uint)sparseBufferData.ChunkOffset
};
var sparseIndicesBufferId = sparse.Indices.BufferView.Value.Buffer;
var sparseIndicesBufferData = await GetBufferData(sparseIndicesBufferId);
AttributeAccessor sparseIndices = new AttributeAccessor
{
AccessorId = attributePair.Value,
Stream = sparseIndicesBufferData.Stream,
Offset = (uint)sparseIndicesBufferData.ChunkOffset
};
sparseAccessors[attributePair.Key] = (sparseIndices, sparseValues);
}
}
if (primitive.Indices != null)
{
var bufferId = primitive.Indices.Value.BufferView.Value.Buffer;
var bufferData = await GetBufferData(bufferId);
attributeAccessors[SemanticProperties.INDICES] = new AttributeAccessor
{
AccessorId = primitive.Indices,
Stream = bufferData.Stream,
Offset = (uint)bufferData.ChunkOffset
};
}
try
{
GLTFHelpers.BuildMeshAttributes(ref attributeAccessors, ref sparseAccessors);
}
catch (GLTFLoadException e)
{
Debug.Log(LogType.Warning, e.ToString());
}
TransformAttributes(ref attributeAccessors);
}
protected void ConvertAttributeAccessorsToUnityTypes(
MeshCacheData.PrimitiveCacheData primData,
UnityMeshData unityData,
int vertOffset,
int indexOffset)
{
// todo optimize: There are multiple copies being performed to turn the buffer data into mesh data. Look into reducing them
var meshAttributes = primData.Attributes;
int vertexCount = (int)meshAttributes[SemanticProperties.POSITION].AccessorId.Value.Count;
var indices = meshAttributes.ContainsKey(SemanticProperties.INDICES)
? meshAttributes[SemanticProperties.INDICES].AccessorContent.AsUInts.ToIntArrayRaw()
: MeshPrimitive.GenerateTriangles(vertexCount);
if (unityData.Topology[indexOffset] == MeshTopology.Triangles)
SchemaExtensions.FlipTriangleFaces(indices);
unityData.Indices[indexOffset] = indices;
if (meshAttributes.ContainsKey(SemanticProperties.Weight[0]) && meshAttributes.ContainsKey(SemanticProperties.Joint[0]))
{
CreateBoneWeightArray(
meshAttributes[SemanticProperties.Joint[0]].AccessorContent.AsVec4s.ToUnityVector4Raw(),
meshAttributes[SemanticProperties.Weight[0]].AccessorContent.AsVec4s.ToUnityVector4Raw(),
ref unityData.BoneWeights,
vertOffset);
}
if (meshAttributes.ContainsKey(SemanticProperties.POSITION))
{
meshAttributes[SemanticProperties.POSITION].AccessorContent.AsVertices.ToUnityVector3Raw(unityData.Vertices, vertOffset);
}
if (meshAttributes.ContainsKey(SemanticProperties.NORMAL))
{
meshAttributes[SemanticProperties.NORMAL].AccessorContent.AsNormals.ToUnityVector3Raw(unityData.Normals, vertOffset);
}
if (meshAttributes.ContainsKey(SemanticProperties.TANGENT))
{
meshAttributes[SemanticProperties.TANGENT].AccessorContent.AsTangents.ToUnityVector4Raw(unityData.Tangents, vertOffset);
}
if (meshAttributes.ContainsKey(SemanticProperties.TexCoord[0]))
{
meshAttributes[SemanticProperties.TexCoord[0]].AccessorContent.AsTexcoords.ToUnityVector2Raw(unityData.Uv1, vertOffset);
}
if (meshAttributes.ContainsKey(SemanticProperties.TexCoord[1]))
{
meshAttributes[SemanticProperties.TexCoord[1]].AccessorContent.AsTexcoords.ToUnityVector2Raw(unityData.Uv2, vertOffset);
}
if (meshAttributes.ContainsKey(SemanticProperties.TexCoord[2]))
{
meshAttributes[SemanticProperties.TexCoord[2]].AccessorContent.AsTexcoords.ToUnityVector2Raw(unityData.Uv3, vertOffset);
}
if (meshAttributes.ContainsKey(SemanticProperties.TexCoord[3]))
{
meshAttributes[SemanticProperties.TexCoord[3]].AccessorContent.AsTexcoords.ToUnityVector2Raw(unityData.Uv4, vertOffset);
}
if (meshAttributes.ContainsKey(SemanticProperties.Color[0]))
{
if (QualitySettings.activeColorSpace == ColorSpace.Gamma)
meshAttributes[SemanticProperties.Color[0]].AccessorContent.AsColors.ToUnityColorRaw(unityData.Colors, vertOffset);
else
meshAttributes[SemanticProperties.Color[0]].AccessorContent.AsColors.ToUnityColorLinear(unityData.Colors, vertOffset);
}
var targets = primData.Targets;
if (targets != null)
{
for (int i = 0; i < targets.Count; ++i)
{
if (targets[i].ContainsKey(SemanticProperties.POSITION))
{
targets[i][SemanticProperties.POSITION].AccessorContent.AsVec3s.ToUnityVector3Raw(unityData.MorphTargetVertices[i], vertOffset);
}
if (targets[i].ContainsKey(SemanticProperties.NORMAL))
{
targets[i][SemanticProperties.NORMAL].AccessorContent.AsVec3s.ToUnityVector3Raw(unityData.MorphTargetNormals[i], vertOffset);
}
if (targets[i].ContainsKey(SemanticProperties.TANGENT))
{
targets[i][SemanticProperties.TANGENT].AccessorContent.AsVec3s.ToUnityVector3Raw(unityData.MorphTargetTangents[i], vertOffset);
}
}
}
}
// Flip vectors to Unity coordinate system
private void TransformTargets(ref Dictionary<string, AttributeAccessor> attributeAccessors)
{
if (attributeAccessors.ContainsKey(SemanticProperties.POSITION))
{
AttributeAccessor attributeAccessor = attributeAccessors[SemanticProperties.POSITION];
SchemaExtensions.ConvertVector3CoordinateSpace(ref attributeAccessor, SchemaExtensions.CoordinateSpaceConversionScale);
}
if (attributeAccessors.ContainsKey(SemanticProperties.NORMAL))
{
AttributeAccessor attributeAccessor = attributeAccessors[SemanticProperties.NORMAL];
SchemaExtensions.ConvertVector3CoordinateSpace(ref attributeAccessor, SchemaExtensions.CoordinateSpaceConversionScale);
}
if (attributeAccessors.ContainsKey(SemanticProperties.TANGENT))
{
AttributeAccessor attributeAccessor = attributeAccessors[SemanticProperties.TANGENT];
SchemaExtensions.ConvertVector3CoordinateSpace(ref attributeAccessor, SchemaExtensions.CoordinateSpaceConversionScale);
}
}
protected void TransformAttributes(ref Dictionary<string, AttributeAccessor> attributeAccessors)
{
foreach (var name in attributeAccessors.Keys)
{
var aa = attributeAccessors[name];
switch (name)
{
case SemanticProperties.POSITION:
case SemanticProperties.NORMAL:
SchemaExtensions.ConvertVector3CoordinateSpace(ref aa, SchemaExtensions.CoordinateSpaceConversionScale);
break;
case SemanticProperties.TANGENT:
SchemaExtensions.ConvertVector4CoordinateSpace(ref aa, SchemaExtensions.TangentSpaceConversionScale);
break;
case SemanticProperties.TEXCOORD_0:
case SemanticProperties.TEXCOORD_1:
case SemanticProperties.TEXCOORD_2:
case SemanticProperties.TEXCOORD_3:
SchemaExtensions.FlipTexCoordArrayV(ref aa);
break;
}
}
}
private static void AddNewBufferAndViewToAccessor(byte[] data, Accessor accessor, GLTFRoot _gltfRoot)
{
_gltfRoot.Buffers.Add(new GLTFBuffer() { ByteLength = (uint) data.Length });
_gltfRoot.BufferViews.Add(new BufferView() { ByteLength = (uint) data.Length, ByteOffset = 0, Buffer = new BufferId() { Id = _gltfRoot.Buffers.Count, Root = _gltfRoot } });
accessor.BufferView = new BufferViewId() { Id = _gltfRoot.BufferViews.Count - 1, Root = _gltfRoot };
}
protected static MeshTopology GetTopology(DrawMode mode)
{
switch (mode)
{
case DrawMode.Points: return MeshTopology.Points;
case DrawMode.Lines: return MeshTopology.Lines;
case DrawMode.LineStrip: return MeshTopology.LineStrip;
case DrawMode.Triangles: return MeshTopology.Triangles;
}
throw new Exception("Unity does not support glTF draw mode: " + mode);
}
/// <summary>
/// Allocate a generic type 2D array. The size is depending on the given parameters.
/// </summary>
/// <param name="x">Defines the depth of the arrays first dimension</param>
/// <param name="y">>Defines the depth of the arrays second dimension</param>
/// <returns></returns>
private static T[][] Allocate2dArray<T>(uint x, uint y)
{
var result = new T[x][];
for (var i = 0; i < x; i++) result[i] = new T[y];
return result;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7f4930a0205140bbbcfaa67b79ab587b
timeCreated: 1657013019
@@ -0,0 +1,97 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using GLTF;
using GLTF.Schema;
using UnityEngine;
using UnityGLTF.Extensions;
using Matrix4x4 = GLTF.Math.Matrix4x4;
using Vector4 = UnityEngine.Vector4;
namespace UnityGLTF
{
public partial class GLTFSceneImporter
{
protected virtual async Task SetupBones(Skin skin, SkinnedMeshRenderer renderer, CancellationToken cancellationToken)
{
var boneCount = skin.Joints.Count;
Transform[] bones = new Transform[boneCount];
// TODO: build bindpose arrays only once per skin, instead of once per node
Matrix4x4[] gltfBindPoses = null;
if (skin.InverseBindMatrices != null)
{
var bufferId = skin.InverseBindMatrices.Value.BufferView.Value.Buffer;
var bufferData = await GetBufferData(bufferId);
AttributeAccessor attributeAccessor = new AttributeAccessor
{
AccessorId = skin.InverseBindMatrices,
Stream = bufferData.Stream,
Offset = bufferData.ChunkOffset
};
GLTFHelpers.BuildBindPoseSamplers(ref attributeAccessor);
gltfBindPoses = attributeAccessor.AccessorContent.AsMatrix4x4s;
}
UnityEngine.Matrix4x4[] bindPoses = new UnityEngine.Matrix4x4[boneCount];
for (int i = 0; i < boneCount; i++)
{
var node = await GetNode(skin.Joints[i].Id, cancellationToken);
bones[i] = node.transform;
bindPoses[i] = gltfBindPoses != null ? gltfBindPoses[i].ToUnityMatrix4x4Convert() : UnityEngine.Matrix4x4.identity;
}
if (skin.Skeleton != null)
{
var rootBoneNode = await GetNode(skin.Skeleton.Id, cancellationToken);
renderer.rootBone = rootBoneNode.transform;
}
else
{
var rootBoneId = GLTFHelpers.FindCommonAncestor(skin.Joints);
if (rootBoneId != null)
{
var rootBoneNode = await GetNode(rootBoneId.Id, cancellationToken);
renderer.rootBone = rootBoneNode.transform;
}
else
{
throw new Exception("glTF skin joints do not share a root node!");
}
}
renderer.sharedMesh.bindposes = bindPoses;
renderer.bones = bones;
}
private void CreateBoneWeightArray(Vector4[] joints, Vector4[] weights, ref BoneWeight[] destArr, int offset = 0)
{
// normalize weights (built-in normalize function only normalizes three components)
for (int i = 0; i < weights.Length; i++)
{
var weightSum = (weights[i].x + weights[i].y + weights[i].z + weights[i].w);
if (!Mathf.Approximately(weightSum, 0))
{
weights[i] /= weightSum;
}
}
for (int i = 0; i < joints.Length; i++)
{
destArr[offset + i].boneIndex0 = (int)joints[i].x;
destArr[offset + i].boneIndex1 = (int)joints[i].y;
destArr[offset + i].boneIndex2 = (int)joints[i].z;
destArr[offset + i].boneIndex3 = (int)joints[i].w;
destArr[offset + i].weight0 = weights[i].x;
destArr[offset + i].weight1 = weights[i].y;
destArr[offset + i].weight2 = weights[i].z;
destArr[offset + i].weight3 = weights[i].w;
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: cef61a6932d545e0aca7bb7cd4a819db
timeCreated: 1657012769
@@ -0,0 +1,444 @@
using System;
using System.IO;
using System.Threading.Tasks;
using GLTF.Schema;
using GLTF.Utilities;
using UnityEngine;
using UnityGLTF.Cache;
using UnityGLTF.Extensions;
using UnityGLTF.Loader;
using Object = UnityEngine.Object;
namespace UnityGLTF
{
public partial class GLTFSceneImporter
{
private class TextureData
{
public Texture Texture = null;
public int TexCoord = 0;
public double DataMultiplier = 1;
public Vector2 Offset = Vector2.zero;
public double Rotation = 0;
public Vector2 Scale = Vector2.one;
public int TexCoordExtra = 0;
}
private async Task<TextureData> FromTextureInfo(TextureInfo textureInfo)
{
var result = new TextureData();
if (textureInfo?.Index?.Value == null) return result;
TextureId textureId = textureInfo.Index;
await ConstructTexture(textureId.Value, textureId.Id, !KeepCPUCopyOfTexture, true);
result.Texture = _assetCache.TextureCache[textureId.Id].Texture;
result.TexCoord = textureInfo.TexCoord;
if (textureInfo is NormalTextureInfo nti)
result.DataMultiplier = nti.Scale;
if (textureInfo is OcclusionTextureInfo oti)
result.DataMultiplier = oti.Strength;
var ext = GetTextureTransform(textureInfo);
if (ext != null)
{
result.Offset = ext.Offset.ToUnityVector2Raw();
result.Rotation = ext.Rotation;
result.Scale = ext.Scale.ToUnityVector2Raw();
result.TexCoordExtra = ext.TexCoord;
}
return result;
}
protected async Task ConstructImage(GLTFImage image, int imageCacheIndex, bool markGpuOnly, bool isLinear)
{
if (_assetCache.ImageCache[imageCacheIndex] == null)
{
Stream stream = null;
if (image.Uri == null)
{
var bufferView = image.BufferView.Value;
var data = new byte[bufferView.ByteLength];
BufferCacheData bufferContents = _assetCache.BufferCache[bufferView.Buffer.Id];
bufferContents.Stream.Position = bufferView.ByteOffset + bufferContents.ChunkOffset;
stream = new SubStream(bufferContents.Stream, 0, data.Length);
}
else
{
string uri = image.Uri;
byte[] bufferData;
URIHelper.TryParseBase64(uri, out bufferData);
if (bufferData != null)
{
stream = new MemoryStream(bufferData, 0, bufferData.Length, false, true);
}
else
{
stream = _assetCache.ImageStreamCache[imageCacheIndex];
}
}
await YieldOnTimeoutAndThrowOnLowMemory();
await ConstructUnityTexture(stream, markGpuOnly, isLinear, image, imageCacheIndex);
}
}
protected async Task ConstructImageBuffer(GLTFTexture texture, int textureIndex)
{
int sourceId = GetTextureSourceId(texture);
if (_assetCache.ImageStreamCache[sourceId] == null)
{
GLTFImage image = _gltfRoot.Images[sourceId];
// we only load the streams if not a base64 uri, meaning the data is in the uri
if (image.Uri != null && !URIHelper.IsBase64Uri(image.Uri))
{
_assetCache.ImageStreamCache[sourceId] = await _options.DataLoader.LoadStreamAsync(image.Uri);
}
else if (image.Uri == null && image.BufferView != null && _assetCache.BufferCache[image.BufferView.Value.Buffer.Id] == null)
{
int bufferIndex = image.BufferView.Value.Buffer.Id;
await ConstructBuffer(_gltfRoot.Buffers[bufferIndex], bufferIndex);
}
}
if (_assetCache.TextureCache[textureIndex] == null)
{
_assetCache.TextureCache[textureIndex] = new TextureCacheData
{
TextureDefinition = texture
};
}
}
async Task CheckMimeTypeAndLoadImage(GLTFImage image, Texture2D texture, byte[] data, bool markGpuOnly)
{
switch (image.MimeType)
{
case "image/png":
case "image/jpeg":
// NOTE: the second parameter of LoadImage() marks non-readable, but we can't mark it until after we call Apply()
texture.LoadImage(data, markGpuOnly);
break;
case "image/ktx2":
#if HAVE_KTX
// TODO doesn't work yet, blocks?
// var ktxTexture = new KtxUnity.KtxTexture();
// using(var alloc = new Unity.Collections.NativeArray<byte>(data, Unity.Collections.Allocator.Persistent))
// {
// var resultTextureData = await ktxTexture.LoadFromBytes(alloc, false);
// var tmp = texture;
// texture = resultTextureData.texture;
// texture.name = tmp.name;
// }
#else
Debug.Log(LogType.Warning, "The KTX2 Texture Format (KHR_texture_basisu) isn't supported right now. The texture " + texture.name + " won't load and will be black. Try using glTFast instead.");
await Task.CompletedTask;
#endif
break;
default:
texture.LoadImage(data, markGpuOnly);
break;
}
await Task.CompletedTask;
}
protected virtual async Task ConstructUnityTexture(Stream stream, bool markGpuOnly, bool isLinear, GLTFImage image, int imageCacheIndex)
{
#if UNITY_EDITOR
if (stream is AssetDatabaseStream assetDatabaseStream)
{
var tx = UnityEditor.AssetDatabase.LoadAssetAtPath<Texture2D>(assetDatabaseStream.AssetUri);
progressStatus.TextureLoaded++;
progress?.Report(progressStatus);
_assetCache.ImageCache[imageCacheIndex] = tx;
return;
}
#endif
Texture2D texture = new Texture2D(0, 0, TextureFormat.RGBA32, GenerateMipMapsForTextures, isLinear);
texture.name = string.IsNullOrEmpty(image.Name) ? Path.GetFileNameWithoutExtension(image.Uri) : image.Name;
if (stream == FileLoader.InvalidStream)
{
// ignore
texture = null;
}
else if (stream is MemoryStream)
{
using (MemoryStream memoryStream = stream as MemoryStream)
{
await YieldOnTimeoutAndThrowOnLowMemory();
await CheckMimeTypeAndLoadImage(image, texture, memoryStream.ToArray(), markGpuOnly);
}
}
else
{
byte[] buffer = new byte[stream.Length];
// todo: potential optimization is to split stream read into multiple frames (or put it on a thread?)
if (stream.Length > int.MaxValue)
{
throw new Exception("Stream is larger than can be copied into byte array");
}
stream.Read(buffer, 0, (int)stream.Length);
await YieldOnTimeoutAndThrowOnLowMemory();
await CheckMimeTypeAndLoadImage(image, texture, buffer, markGpuOnly);
}
if (_assetCache.ImageCache[imageCacheIndex] != null) Debug.Log(LogType.Assert, "ImageCache should not be loaded multiple times");
if (texture)
{
progressStatus.TextureLoaded++;
progress?.Report(progressStatus);
}
_assetCache.ImageCache[imageCacheIndex] = texture;
}
protected virtual int GetTextureSourceId(GLTFTexture texture)
{
return texture.Source?.Id ?? 0;
}
/// <summary>
/// Creates a texture from a glTF texture
/// </summary>
/// <param name="texture">The texture to load</param>
/// <param name="textureIndex">The index in the texture cache</param>
/// <param name="markGpuOnly">Whether the texture is GPU only, instead of keeping a CPU copy</param>
/// <param name="isLinear">Whether the texture is linear rather than sRGB</param>
/// <returns>The loading task</returns>
public virtual async Task LoadTextureAsync(GLTFTexture texture, int textureIndex, bool markGpuOnly, bool isLinear)
{
try
{
lock (this)
{
if (_isRunning)
{
throw new GLTFLoadException("Cannot CreateTexture while GLTFSceneImporter is already running");
}
_isRunning = true;
}
if (_options.ThrowOnLowMemory)
{
_memoryChecker = new MemoryChecker();
}
if (_gltfRoot == null)
{
await LoadJson(_gltfFileName);
}
if (_assetCache == null)
{
_assetCache = new AssetCache(_gltfRoot);
}
await ConstructImageBuffer(texture, textureIndex);
await ConstructTexture(texture, textureIndex, markGpuOnly, isLinear);
}
finally
{
lock (this)
{
_isRunning = false;
}
}
}
public virtual Task LoadTextureAsync(GLTFTexture texture, int textureIndex, bool isLinear)
{
return LoadTextureAsync(texture, textureIndex, !KeepCPUCopyOfTexture, isLinear);
}
/// <summary>
/// Gets texture that has been loaded from CreateTexture
/// </summary>
/// <param name="textureIndex">The texture to get</param>
/// <returns>Created texture</returns>
public virtual Texture GetTexture(int textureIndex)
{
if (_assetCache == null)
{
throw new GLTFLoadException("Asset cache needs initialized before calling GetTexture");
}
if (_assetCache.TextureCache[textureIndex] == null)
{
return null;
}
return _assetCache.TextureCache[textureIndex].Texture;
}
protected virtual async Task ConstructTexture(GLTFTexture texture, int textureIndex, bool markGpuOnly, bool isLinear)
{
if (_assetCache.TextureCache[textureIndex].Texture == null)
{
int sourceId = GetTextureSourceId(texture);
GLTFImage image = _gltfRoot.Images[sourceId];
await ConstructImage(image, sourceId, markGpuOnly, isLinear);
var source = _assetCache.ImageCache[sourceId];
if (!source) return;
FilterMode desiredFilterMode;
TextureWrapMode desiredWrapModeS, desiredWrapModeT;
if (texture.Sampler != null)
{
var sampler = texture.Sampler.Value;
switch (sampler.MinFilter)
{
case MinFilterMode.Nearest:
case MinFilterMode.NearestMipmapNearest:
case MinFilterMode.NearestMipmapLinear:
desiredFilterMode = FilterMode.Point;
break;
case MinFilterMode.Linear:
case MinFilterMode.LinearMipmapNearest:
desiredFilterMode = FilterMode.Bilinear;
break;
case MinFilterMode.LinearMipmapLinear:
desiredFilterMode = FilterMode.Trilinear;
break;
default:
Debug.Log(LogType.Warning, "Unsupported Sampler.MinFilter: " + sampler.MinFilter);
desiredFilterMode = FilterMode.Trilinear;
break;
}
TextureWrapMode UnityWrapMode(GLTF.Schema.WrapMode gltfWrapMode)
{
switch (gltfWrapMode)
{
case GLTF.Schema.WrapMode.ClampToEdge:
return TextureWrapMode.Clamp;
case GLTF.Schema.WrapMode.Repeat:
return TextureWrapMode.Repeat;
case GLTF.Schema.WrapMode.MirroredRepeat:
return TextureWrapMode.Mirror;
default:
Debug.Log(LogType.Warning, "Unsupported Sampler.Wrap: " + gltfWrapMode);
return TextureWrapMode.Repeat;
}
}
desiredWrapModeS = UnityWrapMode(sampler.WrapS);
desiredWrapModeT = UnityWrapMode(sampler.WrapT);
}
else
{
desiredFilterMode = FilterMode.Trilinear;
desiredWrapModeS = TextureWrapMode.Repeat;
desiredWrapModeT = TextureWrapMode.Repeat;
}
var matchSamplerState = source.filterMode == desiredFilterMode && source.wrapModeU == desiredWrapModeS && source.wrapModeV == desiredWrapModeT;
if (matchSamplerState || markGpuOnly)
{
if (_assetCache.TextureCache[textureIndex].Texture != null) Debug.Log(LogType.Assert, "Texture should not be reset to prevent memory leaks");
_assetCache.TextureCache[textureIndex].Texture = source;
if (!matchSamplerState)
{
Debug.Log(LogType.Warning, $"Ignoring sampler; filter mode: source {source.filterMode}, desired {desiredFilterMode}; wrap mode: source {source.wrapModeU}x{source.wrapModeV}, desired {desiredWrapModeS}x{desiredWrapModeT}");
}
}
else
#if UNITY_EDITOR
if (!UnityEditor.AssetDatabase.Contains(source))
#endif
{
var unityTexture = Object.Instantiate(source);
unityTexture.name = string.IsNullOrEmpty(image.Name) ?
string.IsNullOrEmpty(texture.Name) ?
Path.GetFileNameWithoutExtension(image.Uri) :
texture.Name :
image.Name;
unityTexture.filterMode = desiredFilterMode;
unityTexture.wrapModeU = desiredWrapModeS;
unityTexture.wrapModeV = desiredWrapModeT;
if (_assetCache.TextureCache[textureIndex].Texture != null) Debug.Log(LogType.Assert, "Texture should not be reset to prevent memory leaks");
_assetCache.TextureCache[textureIndex].Texture = unityTexture;
}
#if UNITY_EDITOR
else
{
// don't warn for just filter mode, user choice
if (source.wrapModeU != desiredWrapModeS || source.wrapModeV != desiredWrapModeT)
Debug.Log(LogType.Warning, ($"Sampler state doesn't match but source texture is non-readable. Results might not be correct if textures are used multiple times with different sampler states. {source.filterMode} == {desiredFilterMode} && {source.wrapModeU} == {desiredWrapModeS} && {source.wrapModeV} == {desiredWrapModeT}"));
_assetCache.TextureCache[textureIndex].Texture = source;
}
#endif
}
_assetCache.TextureCache[textureIndex].IsLinear = isLinear;
}
protected virtual void ConstructImageFromGLB(GLTFImage image, int imageCacheIndex)
{
var texture = new Texture2D(0, 0);
texture.name = nameof(GLTFSceneImporter) + (image.Name != null ? ("." + image.Name) : "");
var bufferView = image.BufferView.Value;
var data = new byte[bufferView.ByteLength];
var bufferContents = _assetCache.BufferCache[bufferView.Buffer.Id];
bufferContents.Stream.Position = bufferView.ByteOffset + bufferContents.ChunkOffset;
bufferContents.Stream.Read(data, 0, data.Length);
texture.LoadImage(data);
if (_assetCache.ImageCache[imageCacheIndex] != null) Debug.Log(LogType.Assert, "ImageCache should not be loaded multiple times");
progressStatus.TextureLoaded++;
progress?.Report(progressStatus);
_assetCache.ImageCache[imageCacheIndex] = texture;
}
#if UNITY_EDITOR
internal class AssetDatabaseStream : Stream
{
public string AssetUri { get; }
public AssetDatabaseStream(string imageUri)
{
AssetUri = imageUri;
}
public override void Flush() => throw new NotImplementedException();
public override int Read(byte[] buffer, int offset, int count) => throw new NotImplementedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException();
public override void SetLength(long value) => throw new NotImplementedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException();
public override bool CanRead { get; }
public override bool CanSeek { get; }
public override bool CanWrite { get; }
public override long Length { get; }
public override long Position { get; set; }
}
#endif
}
internal static class MatHelper
{
internal static void SetKeyword(this Material material, string keyword, bool state)
{
if (state)
material.EnableKeyword(keyword + "_ON");
else
material.DisableKeyword(keyword + "_ON");
if (material.HasProperty(keyword))
material.SetFloat(keyword, state ? 1 : 0);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 859436f420e4466daa129c3fc03f4480
timeCreated: 1657012139