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,8 @@
fileFormatVersion: 2
guid: 107a7c058d7ad7c43b3656c44c5364b8
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 6cf51abc0e087ca4d8fc223141dd9c09
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("UnityGLTFScripts")]
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 42d7be7539b58434e88dbb233beed600
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,17 @@
using GLTF.Schema;
namespace GLTF
{
public class AttributeAccessor
{
public AccessorId AccessorId { get; set; }
public NumericArray AccessorContent { get; set; }
public System.IO.Stream Stream { get; set; }
public uint Offset { get; set; }
public AttributeAccessor()
{
AccessorContent = new NumericArray();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 05765344adf6fd949b45bc1e4699305a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,40 @@
using System;
namespace GLTF
{
public class GLTFHeaderInvalidException : Exception
{
public GLTFHeaderInvalidException() : base() { }
public GLTFHeaderInvalidException(string message) : base(message) { }
public GLTFHeaderInvalidException(string message, Exception inner) : base(message, inner) { }
#if !WINDOWS_UWP
protected GLTFHeaderInvalidException(System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
{ }
#endif
}
public class GLTFParseException : Exception
{
public GLTFParseException() : base() { }
public GLTFParseException(string message) : base(message) { }
public GLTFParseException(string message, Exception inner) : base(message, inner) { }
#if !WINDOWS_UWP
protected GLTFParseException(System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
{ }
#endif
}
public class GLTFLoadException : Exception
{
public GLTFLoadException() : base() { }
public GLTFLoadException(string message) : base(message) { }
public GLTFLoadException(string message, Exception inner) : base(message, inner) { }
#if !WINDOWS_UWP
protected GLTFLoadException(System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
{ }
#endif
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3f014046747656547b05fa3774ecf051
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a4214d32c6f922940ba2e0df9e1ff758
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,29 @@
using Newtonsoft.Json.Linq;
namespace GLTF.Schema
{
public class EXT_texture_exr : IExtension
{
public const string EXTENSION_NAME = "EXT_texture_exr";
public ImageId source;
public EXT_texture_exr(ImageId source)
{
this.source = source;
}
public IExtension Clone(GLTFRoot root)
{
return new EXT_texture_exr(source);
}
public JProperty Serialize()
{
JObject ext = new JObject();
ext.Add("source", source.Id);
return new JProperty(EXTENSION_NAME, ext);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 9348b48c4902434e81000a832ca2ef33
timeCreated: 1662326250
@@ -0,0 +1,88 @@
using System;
using GLTF.Math;
using GLTF.Schema;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace GLTF.Schema
{
public class ExtTextureTransformExtension : IExtension
{
/// <summary>
/// The offset of the UV coordinate origin as a percentage of the texture dimensions.
/// </summary>
public Vector2 Offset = new Vector2(0, 0);
public static readonly Vector2 OFFSET_DEFAULT = new Vector2(0, 0);
/// <summary>
/// Rotate the UVs by this many radians counter-clockwise around the origin. This is equivalent
/// to a similar rotation of the image clockwise.
/// </summary>
public double Rotation = 0.0f;
public static readonly double ROTATION_DEFAULT = 0.0f;
/// <summary>
/// The scale factor applied to the components of the UV coordinates.
/// </summary>
public Vector2 Scale = new Vector2(1, 1);
public static readonly Vector2 SCALE_DEFAULT = new Vector2(1, 1);
/// <summary>
/// Overrides the textureInfo texCoord value if this extension is supported.
/// </summary>
public int TexCoord = 0;
public static readonly int TEXCOORD_DEFAULT = 0;
public ExtTextureTransformExtension(Vector2 offset, double rotation, Vector2 scale, int texCoord)
{
Offset = offset;
Rotation = rotation;
Scale = scale;
TexCoord = texCoord;
}
public IExtension Clone(GLTFRoot root)
{
return new ExtTextureTransformExtension(Offset, Rotation, Scale, TexCoord);
}
public JProperty Serialize()
{
JObject ext = new JObject();
if (Offset != OFFSET_DEFAULT)
{
ext.Add(new JProperty(
ExtTextureTransformExtensionFactory.OFFSET,
new JArray(Offset.X, Offset.Y)
));
}
if (Rotation != ROTATION_DEFAULT)
{
ext.Add(new JProperty(
ExtTextureTransformExtensionFactory.ROTATION,
Rotation
));
}
if (Scale != SCALE_DEFAULT)
{
ext.Add(new JProperty(
ExtTextureTransformExtensionFactory.SCALE,
new JArray(Scale.X, Scale.Y)
));
}
if (TexCoord != TEXCOORD_DEFAULT)
{
ext.Add(new JProperty(
ExtTextureTransformExtensionFactory.TEXCOORD,
TexCoord
));
}
return new JProperty(ExtTextureTransformExtensionFactory.EXTENSION_NAME, ext);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8f80e6282349fec4b81cd78cd8a9aa00
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,45 @@
using Newtonsoft.Json.Linq;
using GLTF.Extensions;
using GLTF.Math;
namespace GLTF.Schema
{
public class ExtTextureTransformExtensionFactory : ExtensionFactory
{
public const string EXTENSION_NAME = "KHR_texture_transform";
public const string OFFSET = "offset";
public const string ROTATION = "rotation";
public const string SCALE = "scale";
public const string TEXCOORD = "texCoord";
public ExtTextureTransformExtensionFactory()
{
ExtensionName = EXTENSION_NAME;
}
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
{
Vector2 offset = new Vector2(ExtTextureTransformExtension.OFFSET_DEFAULT);
double rotation = 0;
Vector2 scale = new Vector2(ExtTextureTransformExtension.SCALE_DEFAULT);
int texCoord = ExtTextureTransformExtension.TEXCOORD_DEFAULT;
if (extensionToken != null)
{
JToken offsetToken = extensionToken.Value[OFFSET];
offset = offsetToken != null ? offsetToken.DeserializeAsVector2() : offset;
JToken rotationToken = extensionToken.Value[ROTATION];
rotation = rotationToken != null ? rotationToken.DeserializeAsDouble() : rotation;
JToken scaleToken = extensionToken.Value[SCALE];
scale = scaleToken != null ? scaleToken.DeserializeAsVector2() : scale;
JToken texCoordToken = extensionToken.Value[TEXCOORD];
texCoord = texCoordToken != null ? texCoordToken.DeserializeAsInt() : texCoord;
}
return new ExtTextureTransformExtension(offset, rotation, scale, texCoord);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bb5582955db3cc947a57a02c5bfe15aa
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,412 @@
using System;
using System.Collections.Generic;
using GLTF.Math;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using GLTF.Schema;
namespace GLTF.Extensions
{
public static class JsonReaderExtensions
{
public static List<string> ReadStringList(this JsonReader reader)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid array at: {0}", reader.Path));
}
var list = new List<string>();
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
list.Add(reader.Value.ToString());
}
return list;
}
public static List<double> ReadDoubleList(this JsonReader reader)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid array at: {0}", reader.Path));
}
var list = new List<double>();
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
list.Add(double.Parse(reader.Value.ToString()));
}
return list;
}
public static List<int> ReadInt32List(this JsonReader reader)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid array at: {0}", reader.Path));
}
var list = new List<int>();
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
list.Add(int.Parse(reader.Value.ToString()));
}
return list;
}
public static List<T> ReadList<T>(this JsonReader reader, Func<T> deserializerFunc)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid array at: {0}", reader.Path));
}
var list = new List<T>();
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
list.Add(deserializerFunc());
// deserializerFunc can advance to EndArray. We need to check for this case as well.
if (reader.TokenType == JsonToken.EndArray)
{
break;
}
}
return list;
}
public static TextureInfo DeserializeAsTexture(this JToken token, GLTFRoot root)
{
TextureInfo textureInfo = null;
if (token != null)
{
JObject textureObject = token as JObject;
if (textureObject == null)
{
throw new Exception("JToken used for Texture deserialization was not a JObject. It was a " + token.Type.ToString());
}
#if DEBUG
// Broken on il2cpp. Don't ship debug DLLs there.
System.Diagnostics.Debug.WriteLine("textureObject is " + textureObject.Type + " with a value of: " + textureObject[TextureInfo.INDEX].Type + " " + textureObject.ToString());
#endif
int indexVal = textureObject[TextureInfo.INDEX].DeserializeAsInt();
textureInfo = new TextureInfo()
{
Index = new TextureId()
{
Id = indexVal,
Root = root
}
};
if (textureObject.ContainsKey(TextureInfo.TEXCOORD))
{
textureInfo.TexCoord = textureObject[TextureInfo.TEXCOORD].DeserializeAsInt();
}
}
return textureInfo;
}
public static NormalTextureInfo DeserializeAsNormalTexture(this JToken token, GLTFRoot root)
{
var tex = DeserializeAsTexture(token, root);
if (tex != null)
{
var normalTex = new NormalTextureInfo() { Index = tex.Index, TexCoord = tex.TexCoord };
JObject textureObject = token as JObject;
if (textureObject.ContainsKey(NormalTextureInfo.SCALE))
{
normalTex.Scale = textureObject[NormalTextureInfo.SCALE].DeserializeAsDouble();
}
return normalTex;
}
return null;
}
public static int DeserializeAsInt(this JToken token)
{
if (token != null)
{
JValue intValue = token as JValue;
if (intValue == null)
{
throw new Exception("JToken used for int deserialization was not a JValue. It was a " + token.Type.ToString());
}
return (int)intValue;
}
return 0;
}
public static double DeserializeAsDouble(this JToken token)
{
if (token != null)
{
JValue doubleValue = token as JValue;
if (doubleValue == null)
{
throw new Exception("JToken used for double deserialization was not a JValue. It was a " + token.Type.ToString());
}
return (double)doubleValue;
}
return 0d;
}
public static Color ReadAsRGBAColor(this JsonReader reader)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid color value at: {0}", reader.Path));
}
var color = new Color
{
R = (float) reader.ReadAsDouble().Value,
G = (float) reader.ReadAsDouble().Value,
B = (float) reader.ReadAsDouble().Value,
A = (float) reader.ReadAsDouble().Value
};
if (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
throw new Exception(string.Format("Invalid color value at: {0}", reader.Path));
}
return color;
}
public static Color DeserializeAsColor(this JToken token)
{
Color color = Color.White;
if (token != null)
{
JArray colorArray = token as JArray;
if (colorArray == null)
{
throw new Exception("JToken used for Color deserialization was not a JArray. It was a " + token.Type.ToString());
}
if (colorArray.Count < 3)
{
throw new Exception("JArray used for Color deserialization did have less than 3 entries (needs to be RGB or RGBA). It had " + colorArray.Count);
}
color = new Color
{
R = (float)colorArray[0].DeserializeAsDouble(),
G = (float)colorArray[1].DeserializeAsDouble(),
B = (float)colorArray[2].DeserializeAsDouble(),
A = (float)(colorArray.Count == 4 ? colorArray[3].DeserializeAsDouble() : 1.0),
};
}
return color;
}
public static Color ReadAsRGBColor(this JsonReader reader)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path));
}
var color = new Color
{
R = (float) reader.ReadAsDouble().Value,
G = (float) reader.ReadAsDouble().Value,
B = (float) reader.ReadAsDouble().Value,
A = 1.0f
};
if (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
throw new Exception(string.Format("Invalid color value at: {0}", reader.Path));
}
return color;
}
public static Vector3 ReadAsVector3(this JsonReader reader)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path));
}
var vector = new Vector3
{
X = (float) reader.ReadAsDouble().Value,
Y = (float) reader.ReadAsDouble().Value,
Z = (float) reader.ReadAsDouble().Value
};
if (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path));
}
return vector;
}
public static Vector2 DeserializeAsVector2(this JToken token)
{
Vector2 vector = new Vector2();
if (token != null)
{
JArray vectorArray = token as JArray;
if (vectorArray == null)
{
throw new Exception("JToken used for Vector2 deserialization was not a JArray. It was a " + token.Type.ToString());
}
if (vectorArray.Count != 2)
{
throw new Exception("JArray used for Vector2 deserialization did not have 2 entries for XY. It had " + vectorArray.Count);
}
vector = new Vector2
{
X = (float)vectorArray[0].DeserializeAsDouble(),
Y = (float)vectorArray[1].DeserializeAsDouble()
};
}
return vector;
}
public static Vector3 DeserializeAsVector3(this JToken token)
{
Vector3 vector = new Vector3();
if (token != null)
{
JArray vectorArray = token as JArray;
if (vectorArray == null)
{
throw new Exception("JToken used for Vector3 deserialization was not a JArray. It was a " + token.Type.ToString());
}
if (vectorArray.Count != 3)
{
throw new Exception("JArray used for Vector3 deserialization did not have 3 entries for XYZ. It had " + vectorArray.Count);
}
vector = new Vector3
{
X = (float)vectorArray[0].DeserializeAsDouble(),
Y = (float)vectorArray[1].DeserializeAsDouble(),
Z = (float)vectorArray[2].DeserializeAsDouble()
};
}
return vector;
}
public static Quaternion ReadAsQuaternion(this JsonReader reader)
{
if (reader.Read() && reader.TokenType != JsonToken.StartArray)
{
throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path));
}
var quat = new Quaternion
{
X = (float) reader.ReadAsDouble().Value,
Y = (float) reader.ReadAsDouble().Value,
Z = (float) reader.ReadAsDouble().Value,
W = (float) reader.ReadAsDouble().Value
};
if (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path));
}
return quat;
}
public static Dictionary<string, T> ReadAsDictionary<T>(this JsonReader reader, Func<T> deserializerFunc, bool skipStartObjectRead = false)
{
if (!skipStartObjectRead && reader.Read() && reader.TokenType != JsonToken.StartObject)
{
throw new Exception(string.Format("Dictionary must be an object at: {0}.", reader.Path));
}
var dict = new Dictionary<string, T>();
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
{
dict.Add(reader.Value.ToString(), deserializerFunc());
}
return dict;
}
public static Dictionary<string, object> ReadAsObjectDictionary(this JsonReader reader, bool skipStartObjectRead = false)
{
if (!skipStartObjectRead && reader.Read() && reader.TokenType != JsonToken.StartObject)
{
throw new Exception(string.Format("Dictionary must be an object at: {0}", reader.Path));
}
var dict = new Dictionary<string, object>();
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
{
dict.Add(reader.Value.ToString(), ReadDictionaryValue(reader));
}
return dict;
}
private static object ReadDictionaryValue(JsonReader reader)
{
if (!reader.Read())
{
return null;
}
switch (reader.TokenType)
{
case JsonToken.StartArray:
return reader.ReadObjectList();
case JsonToken.StartObject:
return reader.ReadAsObjectDictionary(true);
default:
return reader.Value;
}
}
private static List<object> ReadObjectList(this JsonReader reader)
{
var list = new List<object>();
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
list.Add(reader.Value);
}
return list;
}
public static T ReadStringEnum<T>(this JsonReader reader)
{
return (T) Enum.Parse(typeof(T), reader.ReadAsString());
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1b39ce55534dbbf4ab3dceec1cec6317
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,392 @@
using System;
using System.Collections.Generic;
using GLTF.Math;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using GLTF.Extensions;
namespace GLTF.Schema.KHR_lights_punctual
{
/// <summary>
/// Specifies the light type.
/// </summary>
public enum LightType
{
directional,
point,
spot
}
/// <summary>
/// Texture sampler properties for filtering and wrapping modes.
/// </summary>
public class Spot
{
private const string PNAME_INNERCONEANGLE = "innerConeAngle";
private const string PNAME_OUTERCONEANGLE = "outerConeAngle";
public static readonly double INNER_DEFAULT = 0d;
public static readonly double OUTER_DEFAULT = 0.7853981633974483d;
/// <summary>
/// Angle, in radians, from centre of spotlight where falloff begins. Must be greater than or equal to 0 and less than outerConeAngle.
/// </summary>
public double InnerConeAngle = INNER_DEFAULT;
/// <summary>
/// Angle, in radians, from centre of spotlight where falloff ends. Must be greater than innerConeAngle and less than or equal to PI / 2.0.
/// </summary>
public double OuterConeAngle = OUTER_DEFAULT;
public Spot()
{
}
public static Spot Deserialize(JsonReader reader)
{
var spot = new Spot();
if (reader.Read() && reader.TokenType != JsonToken.StartObject)
{
return spot;
}
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
{
var curProp = reader.Value.ToString();
switch (curProp)
{
case PNAME_INNERCONEANGLE:
spot.InnerConeAngle= reader.ReadAsDouble().Value;
break;
case PNAME_OUTERCONEANGLE:
spot.OuterConeAngle= reader.ReadAsDouble().Value;
break;
}
}
return spot;
}
public void Serialize(JsonWriter writer)
{
if( InnerConeAngle > OuterConeAngle)
{
throw new Exception("Spot's InnerConeAngle must be less or equal OuterConeAngle");
}
if (OuterConeAngle > 1.5707963267948966d )
{
throw new Exception("Spot's OuterConeAngle must be less or equal Pi/2");
}
writer.WriteStartObject();
if (InnerConeAngle != INNER_DEFAULT)
{
writer.WritePropertyName(PNAME_INNERCONEANGLE);
writer.WriteValue(InnerConeAngle);
}
if (OuterConeAngle != OUTER_DEFAULT)
{
writer.WritePropertyName(PNAME_OUTERCONEANGLE);
writer.WriteValue(OuterConeAngle);
}
writer.WriteEndObject();
}
}
public class PunctualLight : GLTFChildOfRootProperty
{
private const string PNAME_TYPE = "type";
private const string PNAME_COLOR = "color";
private const string PNAME_INTENSITY = "intensity";
private const string PNAME_RANGE = "range";
private const string PNAME_SPOT = "spot";
public static readonly Color COLOR_DEFAULT = Color.White;
public static readonly double RANGE_DEFAULT = -1d;
public static readonly double INTENSITY_DEFAULT = 1d;
/// <summary>
/// Specifies the light type.
/// </summary>
public LightType Type;
/// <summary>
/// Color of the light source.
/// </summary>
public Color Color = COLOR_DEFAULT;
/// <summary>
/// Intensity of the light source. `point` and `spot` lights use luminous intensity in candela (lm/sr) while `directional` lights use illuminance in lux (lm/m^2)
/// </summary>
public double Intensity = INTENSITY_DEFAULT;
/// <summary>
/// A distance cutoff at which the light's intensity may be considered to have reached zero.
/// </summary>
public double Range = RANGE_DEFAULT;
/// <summary>
/// spot's inner and outer angle, must exist for spot types
/// </summary>
public Spot Spot;
public PunctualLight()
{
}
public PunctualLight(PunctualLight light, GLTFRoot gltfRoot) : base(light, gltfRoot)
{
Type = light.Type;
Color = light.Color;
Intensity = light.Intensity;
Range = light.Range;
Spot = light.Spot;
}
public static PunctualLight Deserialize(GLTFRoot root, JsonReader reader)
{
var light = new PunctualLight();
if (reader.Read() && reader.TokenType != JsonToken.StartObject)
{
throw new Exception("Light must be an object.");
}
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
{
var curProp = reader.Value.ToString();
switch (curProp)
{
case PNAME_TYPE:
light.Type = reader.ReadStringEnum<LightType>();
break;
case PNAME_COLOR:
light.Color = reader.ReadAsRGBColor();
break;
case PNAME_INTENSITY:
light.Intensity = reader.ReadAsDouble().Value;
break;
case PNAME_RANGE:
light.Range = reader.ReadAsDouble().Value;
break;
case PNAME_SPOT:
light.Spot = Spot.Deserialize(reader);
break;
default:
light.DefaultPropertyDeserializer(root, reader);
break;
}
}
return light;
}
public static PunctualLight Deserialize(GLTFRoot root, JToken token)
{
using (JsonReader reader = new JTokenReader(token))
{
return Deserialize(root, reader);
}
}
override public void Serialize(JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName(PNAME_TYPE);
writer.WriteValue(Type.ToString());
if (Color != COLOR_DEFAULT)
{
writer.WritePropertyName(PNAME_COLOR);
writer.WriteStartArray();
writer.WriteValue(Color.R);
writer.WriteValue(Color.G);
writer.WriteValue(Color.B);
writer.WriteEndArray();
}
if (Intensity != INTENSITY_DEFAULT)
{
writer.WritePropertyName(PNAME_INTENSITY);
writer.WriteValue(Intensity);
}
if (Range != RANGE_DEFAULT)
{
writer.WritePropertyName(PNAME_RANGE);
writer.WriteValue(Range);
}
if (Type == LightType.spot)
{
writer.WritePropertyName(PNAME_SPOT);
Spot.Serialize(writer);
}
base.Serialize(writer);
writer.WriteEndObject();
}
public JObject Serialize()
{
JTokenWriter writer = new JTokenWriter();
Serialize(writer);
return (JObject)writer.Token;
}
}
public class KHR_LightsPunctualRootExtension : IExtension
{
public const string EXTENSION_NAME = "KHR_lights_punctual";
public readonly IList<GLTFLight> lights;
public KHR_LightsPunctualRootExtension(IList<GLTFLight> lights)
{
this.lights = lights;
}
public JProperty Serialize()
{
var obj = new JObject();
var arr = new JArray();
obj.Add("lights", arr);
foreach (var light in lights)
{
var lightInfo = new JObject();
arr.Add(lightInfo);
lightInfo.Add("type", light.type);
if (light.range > 0) lightInfo.Add("range", light.range);
if(System.Math.Abs(light.intensity - 1f) > .0000001) lightInfo.Add("intensity", light.intensity);
lightInfo.Add("name", light.Name ?? light.name);
lightInfo.Add("color", new JArray(light.color.R, light.color.G, light.color.B));
// TODO why is this not using the specific spotlight serializer/deserializer?
if (light is GLTFSpotLight spotLight)
{
lightInfo.Add("spot", new JObject(
new JProperty(nameof(spotLight.innerConeAngle), spotLight.innerConeAngle),
new JProperty(nameof(spotLight.outerConeAngle), spotLight.outerConeAngle)));
}
}
return new JProperty(EXTENSION_NAME, obj);
}
public IExtension Clone(GLTFRoot root)
{
return new KHR_LightsPunctualRootExtension(lights);
}
}
public class KHR_LightsPunctualExtension : IExtension
{
public List<PunctualLight> Lights;
public KHR_LightsPunctualExtension()
{
Lights = new List<PunctualLight>();
}
public IExtension Clone(GLTFRoot root)
{
var clone = new KHR_LightsPunctualExtension();
for (int i = 0; i < Lights.Count; i++)
{
clone.Lights.Add(new PunctualLight(Lights[i], root));
}
return clone;
}
public JProperty Serialize()
{
return new JProperty(KHR_lights_punctualExtensionFactory.EXTENSION_NAME,
new JObject(
new JProperty(KHR_lights_punctualExtensionFactory.PNAME_LIGHTS, new JArray(Lights))
)
);
}
}
public class PunctualLightId : GLTFId<PunctualLight>
{
public PunctualLightId()
{
}
public PunctualLightId(PunctualLightId id, GLTFRoot newRoot) : base(id, newRoot)
{
}
public override PunctualLight Value
{
get
{
if (Root.Extensions.TryGetValue(KHR_lights_punctualExtensionFactory.EXTENSION_NAME, out IExtension iextension))
{
KHR_LightsPunctualExtension extension = iextension as KHR_LightsPunctualExtension;
return extension.Lights[Id];
}
else
{
throw new Exception("KHR_lights_punctual not found on root object");
}
}
}
public static PunctualLightId Deserialize(GLTFRoot root, JsonReader reader)
{
return new PunctualLightId
{
Id = reader.ReadAsInt32().Value,
Root = root
};
}
}
public class KHR_LightsPunctualNodeExtension : IExtension
{
public PunctualLightId LightId;
public KHR_LightsPunctualNodeExtension()
{
}
public KHR_LightsPunctualNodeExtension(PunctualLightId lightId, GLTFRoot gltfRoot)
{
LightId = lightId;
}
public KHR_LightsPunctualNodeExtension( int lightId, GLTFRoot gltfRoot)
{
LightId = new PunctualLightId
{
Id = lightId,
Root = gltfRoot
};
}
public IExtension Clone(GLTFRoot root)
{
return new KHR_LightsPunctualNodeExtension(LightId.Id, root);
}
public JProperty Serialize()
{
return new JProperty(KHR_lights_punctualExtensionFactory.EXTENSION_NAME,
new JObject(
new JProperty(KHR_lights_punctualExtensionFactory.PNAME_LIGHT, LightId.Id )
)
);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8451131b54699e840ba8425046aec379
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,49 @@
using Newtonsoft.Json.Linq;
namespace GLTF.Schema.KHR_lights_punctual
{
public class KHR_lights_punctualExtensionFactory : ExtensionFactory
{
public const string EXTENSION_NAME = "KHR_lights_punctual";
public const string PNAME_LIGHTS = "lights";
public const string PNAME_LIGHT = "light";
public KHR_lights_punctualExtensionFactory()
{
ExtensionName = EXTENSION_NAME;
}
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
{
if (extensionToken != null)
{
JToken lightsToken = extensionToken.Value[PNAME_LIGHTS];
if (lightsToken != null)
{
var extension = new KHR_LightsPunctualExtension();
JArray lightsArray = lightsToken as JArray;
foreach( var lightToken in lightsArray.Children())
{
extension.Lights.Add(PunctualLight.Deserialize(root, lightToken));
}
return extension;
}
JToken nodelightToken = extensionToken.Value[PNAME_LIGHT];
if (nodelightToken != null)
{
PunctualLightId lightId = PunctualLightId.Deserialize(root, nodelightToken.CreateReader() );
return new KHR_LightsPunctualNodeExtension( lightId, root );
}
}
return null;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f6f51e6a8e36a7641bde14286a98f0d5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,38 @@
using GLTF.Schema;
using Newtonsoft.Json.Linq;
namespace UnityGLTF.Extensions
{
// see https://github.com/KhronosGroup/glTF/pull/2147
public class KHR_animation_pointer : IExtension
{
public const string EXTENSION_NAME = "KHR_animation_pointer";
public object animatedObject;
public string propertyBinding;
public string path;
public AnimationChannelTarget channel;
// when cloned, the path is late resolved in gltf exporter so the clone path will not be resolved because it wont be registered to the exporter's resolver
private KHR_animation_pointer clonedFrom;
public JProperty Serialize()
{
if (path == null && clonedFrom != null) path = clonedFrom.path;
return new JProperty(EXTENSION_NAME, new JObject(new JProperty("pointer", path)));
}
public IExtension Clone(GLTFRoot root)
{
return new KHR_animation_pointer
{
animatedObject = animatedObject,
propertyBinding = propertyBinding,
path = path,
channel = channel,
clonedFrom = this
};
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 674db370468f4e2491e20dbadfa2a640
timeCreated: 1648456390
@@ -0,0 +1,96 @@
using System;
using GLTF.Extensions;
using GLTF.Math;
using Newtonsoft.Json.Linq;
namespace GLTF.Schema
{
// https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_clearcoat/README.md
[Serializable]
public class KHR_materials_clearcoat : IExtension
{
public float clearcoatFactor = 0f;
public TextureInfo clearcoatTexture; // R channel
public float clearcoatRoughnessFactor = 0f;
public TextureInfo clearcoatRoughnessTexture; // G channel
public TextureInfo clearcoatNormalTexture;
public JProperty Serialize()
{
var jo = new JObject();
JProperty jProperty = new JProperty(KHR_materials_clearcoat_Factory.EXTENSION_NAME, jo);
// TODO all these properties should only be added if non-default
if (clearcoatFactor != 0)
jo.Add(new JProperty(nameof(clearcoatFactor), clearcoatFactor));
if (clearcoatTexture != null) {
jo.Add(new JProperty(nameof(clearcoatTexture),
new JObject(
new JProperty(TextureInfo.INDEX, clearcoatTexture.Index.Id),
new JProperty(TextureInfo.TEXCOORD, clearcoatTexture.TexCoord)
)
)
);
}
if (clearcoatRoughnessFactor != 0)
jo.Add(new JProperty(nameof(clearcoatRoughnessFactor), clearcoatRoughnessFactor));
if (clearcoatRoughnessTexture != null) {
jo.Add(new JProperty(nameof(clearcoatRoughnessTexture),
new JObject(
new JProperty(TextureInfo.INDEX, clearcoatRoughnessTexture.Index.Id),
new JProperty(TextureInfo.TEXCOORD, clearcoatRoughnessTexture.TexCoord)
)
)
);
}
if (clearcoatNormalTexture != null) {
jo.Add(new JProperty(nameof(clearcoatNormalTexture),
new JObject(
new JProperty(TextureInfo.INDEX, clearcoatNormalTexture.Index.Id),
new JProperty(TextureInfo.TEXCOORD, clearcoatNormalTexture.TexCoord)
// new JProperty(NormalTextureInfo.SCALE, clearcoatNormalTexture.Scale) // TODO needs better normal scale export, uses only the base normal right now
)
)
);
}
return jProperty;
}
public IExtension Clone(GLTFRoot root)
{
return new KHR_materials_clearcoat()
{
clearcoatFactor = clearcoatFactor, clearcoatTexture = clearcoatTexture,
clearcoatRoughnessFactor = clearcoatRoughnessFactor, clearcoatRoughnessTexture = clearcoatRoughnessTexture,
clearcoatNormalTexture = clearcoatNormalTexture,
};
}
}
public class KHR_materials_clearcoat_Factory : ExtensionFactory
{
public const string EXTENSION_NAME = "KHR_materials_clearcoat";
public KHR_materials_clearcoat_Factory()
{
ExtensionName = EXTENSION_NAME;
}
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
{
if (extensionToken != null)
{
var extension = new KHR_materials_clearcoat();
extension.clearcoatFactor = extensionToken.Value[nameof(KHR_materials_clearcoat.clearcoatFactor)]?.Value<float>() ?? 0;
extension.clearcoatTexture = extensionToken.Value[nameof(KHR_materials_clearcoat.clearcoatTexture)]?.DeserializeAsTexture(root);
extension.clearcoatRoughnessFactor = extensionToken.Value[nameof(KHR_materials_clearcoat.clearcoatRoughnessFactor)]?.Value<float>() ?? 0;
extension.clearcoatRoughnessTexture = extensionToken.Value[nameof(KHR_materials_clearcoat.clearcoatRoughnessTexture)]?.DeserializeAsTexture(root);
extension.clearcoatNormalTexture = extensionToken.Value[nameof(KHR_materials_clearcoat.clearcoatNormalTexture)]?.DeserializeAsTexture(root);
return extension;
}
return null;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8427a62b522f4f2d84dda8d98fa76701
timeCreated: 1673353427
@@ -0,0 +1,56 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace GLTF.Schema
{
public class KHR_materials_emissive_strength : GLTFProperty, IExtension
{
public KHR_materials_emissive_strength() { }
public KHR_materials_emissive_strength(KHR_materials_emissive_strength ext, GLTFRoot root) : base(ext, root) { }
public IExtension Clone(GLTFRoot gltfRoot)
{
return new KHR_materials_emissive_strength(this, gltfRoot);
}
public JProperty Serialize()
{
var jo = new JObject();
JProperty jProperty = new JProperty(KHR_materials_emissive_strength_Factory.EXTENSION_NAME, jo);
if(emissiveStrength != 1.0f)
jo.Add(new JProperty(nameof(emissiveStrength), emissiveStrength));
return jProperty;
}
public float emissiveStrength = 1.0f;
}
public class KHR_materials_emissive_strength_Factory : ExtensionFactory
{
public const string EXTENSION_NAME = "KHR_materials_emissive_strength";
public KHR_materials_emissive_strength_Factory()
{
ExtensionName = EXTENSION_NAME;
}
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
{
if (extensionToken != null)
{
var extension = new KHR_materials_emissive_strength();
JToken strength = extensionToken.Value[nameof(KHR_materials_emissive_strength.emissiveStrength)];
if (strength != null)
extension.emissiveStrength = strength.Value<float>();
return extension;
}
return null;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f4a07b6badfb6844e8d34a3a9b15a6f5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,53 @@
using System;
using Newtonsoft.Json.Linq;
namespace GLTF.Schema
{
// https: //github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_ior
[Serializable]
public class KHR_materials_ior : IExtension
{
public const float DefaultIor = 1.5f;
public float ior = 1.5f;
public JProperty Serialize()
{
var obj = new JObject();
if (System.Math.Abs(ior - DefaultIor) > 0.00001f)
obj.Add(new JProperty(nameof(ior), ior));
JProperty jProperty = new JProperty(KHR_materials_ior_Factory.EXTENSION_NAME, obj);
return jProperty;
}
public IExtension Clone(GLTFRoot root)
{
return new KHR_materials_ior() { ior = ior };
}
}
public class KHR_materials_ior_Factory : ExtensionFactory
{
public const string EXTENSION_NAME = "KHR_materials_ior";
public KHR_materials_ior_Factory()
{
ExtensionName = EXTENSION_NAME;
}
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
{
if (extensionToken != null)
{
JToken strength = extensionToken.Value[nameof(KHR_materials_ior.ior)];
var extension = new KHR_materials_ior();
if (strength != null)
{
extension.ior = strength.Value<float>();
}
return extension;
}
return null;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e7620ff271fb4b39934ce610b28e27ef
timeCreated: 1653603717
@@ -0,0 +1,88 @@
using System;
using GLTF.Extensions;
using Newtonsoft.Json.Linq;
using Color = GLTF.Math.Color;
namespace GLTF.Schema
{
// https://github.com/ux3d/glTF/tree/extensions/KHR_materials_iridescence/extensions/2.0/Khronos/KHR_materials_iridescence
[Serializable]
public class KHR_materials_iridescence : IExtension
{
public float iridescenceFactor = 0f;
public TextureInfo iridescenceTexture; // R channel
public float iridescenceIor = 1.3f;
public float iridescenceThicknessMinimum = 100.0f;
public float iridescenceThicknessMaximum = 400.0f;
public TextureInfo iridescenceThicknessTexture; // G channel
public static readonly Color COLOR_DEFAULT = Color.White;
public JProperty Serialize()
{
var jo = new JObject();
JProperty jProperty = new JProperty(KHR_materials_iridescence_Factory.EXTENSION_NAME, jo);
if (iridescenceFactor != 0) jo.Add(new JProperty(nameof(iridescenceFactor), iridescenceFactor));
if (iridescenceIor != 1.3f) jo.Add(new JProperty(nameof(iridescenceIor), iridescenceIor));
if (iridescenceThicknessMinimum != 100.0f) jo.Add(new JProperty(nameof(iridescenceThicknessMinimum), iridescenceThicknessMinimum));
if (iridescenceThicknessMaximum != 400.0f) jo.Add(new JProperty(nameof(iridescenceThicknessMaximum), iridescenceThicknessMaximum));
if (iridescenceTexture != null) {
jo.Add(new JProperty(nameof(iridescenceTexture),
new JObject(
new JProperty(TextureInfo.INDEX, iridescenceTexture.Index.Id),
new JProperty(TextureInfo.TEXCOORD, iridescenceTexture.TexCoord)
)
)
);
}
if (iridescenceThicknessTexture != null) {
jo.Add(new JProperty(nameof(iridescenceThicknessTexture),
new JObject(
new JProperty(TextureInfo.INDEX, iridescenceThicknessTexture.Index.Id),
new JProperty(TextureInfo.TEXCOORD, iridescenceThicknessTexture.TexCoord)
)
)
);
}
return jProperty;
}
public IExtension Clone(GLTFRoot root)
{
return new KHR_materials_iridescence()
{
iridescenceFactor = iridescenceFactor, iridescenceIor = iridescenceIor,
iridescenceThicknessMinimum = iridescenceThicknessMinimum, iridescenceThicknessMaximum = iridescenceThicknessMaximum,
iridescenceTexture = iridescenceTexture, iridescenceThicknessTexture = iridescenceThicknessTexture,
};
}
}
public class KHR_materials_iridescence_Factory : ExtensionFactory
{
public const string EXTENSION_NAME = "KHR_materials_iridescence";
public KHR_materials_iridescence_Factory()
{
ExtensionName = EXTENSION_NAME;
}
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
{
if (extensionToken != null)
{
var extension = new KHR_materials_iridescence();
extension.iridescenceFactor = extensionToken.Value[nameof(KHR_materials_iridescence.iridescenceFactor)]?.Value<float>() ?? 0;
extension.iridescenceIor = extensionToken.Value[nameof(KHR_materials_iridescence.iridescenceIor)]?.Value<float>() ?? 1.3f;
extension.iridescenceThicknessMinimum = extensionToken.Value[nameof(KHR_materials_iridescence.iridescenceThicknessMinimum)]?.Value<float>() ?? 100f;
extension.iridescenceThicknessMaximum = extensionToken.Value[nameof(KHR_materials_iridescence.iridescenceThicknessMaximum)]?.Value<float>() ?? 400f;
extension.iridescenceTexture = extensionToken.Value[nameof(KHR_materials_iridescence.iridescenceTexture)]?.DeserializeAsTexture(root);
extension.iridescenceThicknessTexture = extensionToken.Value[nameof(KHR_materials_iridescence.iridescenceThicknessTexture)]?.DeserializeAsTexture(root);
return extension;
}
return null;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 0702e45c391babb47b93be6ff38f4e3e
timeCreated: 1653603693
@@ -0,0 +1,98 @@
using GLTF.Math;
using GLTF.Schema;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace GLTF.Schema
{
/// <summary>
/// glTF extension that defines the specular-glossiness
/// material model from Physically-Based Rendering (PBR) methodology.
///
/// Spec can be found here:
/// https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
/// </summary>
public class KHR_materials_pbrSpecularGlossinessExtension : IExtension
{
public static readonly Vector3 SPEC_FACTOR_DEFAULT = new Vector3(1.0f, 1.0f, 1.0f);
public static readonly double GLOSS_FACTOR_DEFAULT = 1.0d;
/// <summary>
/// The RGBA components of the reflected diffuse color of the material.
/// Metals have a diffuse value of [0.0, 0.0, 0.0].
/// The fourth component (A) is the alpha coverage of the material.
/// The <see cref="GLTFMaterial.AlphaMode"/> property specifies how alpha is interpreted.
/// The values are linear.
/// </summary>
public Color DiffuseFactor = Color.White;
public static readonly Color DIFFUSE_FACTOR_DEFAULT = Color.White;
/// <summary>
/// The diffuse texture.
/// This texture contains RGB(A) components of the reflected diffuse color of the material in sRGB color space.
/// If the fourth component (A) is present, it represents the alpha coverage of the
/// material. Otherwise, an alpha of 1.0 is assumed.
/// The <see cref="GLTFMaterial.AlphaMode"/> property specifies how alpha is interpreted.
/// The stored texels must not be premultiplied.
/// </summary>
public TextureInfo DiffuseTexture;
public static readonly TextureInfo DIFFUSE_TEXTURE_DEFAULT = new TextureInfo();
/// <summary>
/// The specular RGB color of the material. This value is linear
/// </summary>
public Vector3 SpecularFactor = SPEC_FACTOR_DEFAULT;
/// <summary>
/// The glossiness or smoothness of the material.
/// A value of 1.0 means the material has full glossiness or is perfectly smooth.
/// A value of 0.0 means the material has no glossiness or is completely rough.
/// This value is linear.
/// </summary>
public double GlossinessFactor = GLOSS_FACTOR_DEFAULT;
/// <summary>
/// The specular-glossiness texture is RGBA texture, containing the specular color of the material (RGB components) and its glossiness (A component).
/// The values are in sRGB space.
/// </summary>
public TextureInfo SpecularGlossinessTexture;
public static readonly TextureInfo SPECULAR_GLOSSINESS_TEXTURE_DEFAULT = new TextureInfo();
public KHR_materials_pbrSpecularGlossinessExtension(Color diffuseFactor, TextureInfo diffuseTexture, Vector3 specularFactor, double glossinessFactor, TextureInfo specularGlossinessTexture)
{
DiffuseFactor = diffuseFactor;
DiffuseTexture = diffuseTexture;
SpecularFactor = specularFactor;
GlossinessFactor = glossinessFactor;
SpecularGlossinessTexture = specularGlossinessTexture;
}
public IExtension Clone(GLTFRoot gltfRoot)
{
return new KHR_materials_pbrSpecularGlossinessExtension(
DiffuseFactor,
DiffuseTexture != null ? new TextureInfo(DiffuseTexture, gltfRoot) : null,
SpecularFactor,
GlossinessFactor,
SpecularGlossinessTexture != null ? new TextureInfo(SpecularGlossinessTexture, gltfRoot) : null);
}
public JProperty Serialize()
{
var jo = new JObject();
jo.Add(KHR_materials_pbrSpecularGlossinessExtensionFactory.DIFFUSE_FACTOR, new JArray(DiffuseFactor.R, DiffuseFactor.G, DiffuseFactor.B, DiffuseFactor.A));
if(DiffuseTexture != null && DiffuseTexture.Index != null)
jo.Add(KHR_materials_pbrSpecularGlossinessExtensionFactory.DIFFUSE_TEXTURE, new JObject(
new JProperty(TextureInfo.INDEX, DiffuseTexture.Index.Id)));
jo.Add(KHR_materials_pbrSpecularGlossinessExtensionFactory.SPECULAR_FACTOR, new JArray(SpecularFactor.X, SpecularFactor.Y, SpecularFactor.Z));
jo.Add(KHR_materials_pbrSpecularGlossinessExtensionFactory.GLOSSINESS_FACTOR, GlossinessFactor);
if(SpecularGlossinessTexture != null && SpecularGlossinessTexture.Index != null)
jo.Add(KHR_materials_pbrSpecularGlossinessExtensionFactory.SPECULAR_GLOSSINESS_TEXTURE, new JObject(
new JProperty(TextureInfo.INDEX, SpecularGlossinessTexture.Index.Id)));
JProperty jProperty = new JProperty(KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME, jo);
return jProperty;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 59da86adeec3c394c9ba4e017a23db4a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,51 @@
using System;
using Newtonsoft.Json.Linq;
using GLTF.Math;
using Newtonsoft.Json;
using GLTF.Extensions;
namespace GLTF.Schema
{
public class KHR_materials_pbrSpecularGlossinessExtensionFactory : ExtensionFactory
{
public const string EXTENSION_NAME = "KHR_materials_pbrSpecularGlossiness";
public const string DIFFUSE_FACTOR = "diffuseFactor";
public const string DIFFUSE_TEXTURE = "diffuseTexture";
public const string SPECULAR_FACTOR = "specularFactor";
public const string GLOSSINESS_FACTOR = "glossinessFactor";
public const string SPECULAR_GLOSSINESS_TEXTURE = "specularGlossinessTexture";
public KHR_materials_pbrSpecularGlossinessExtensionFactory()
{
ExtensionName = EXTENSION_NAME;
}
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
{
Color diffuseFactor = Color.White;
TextureInfo diffuseTextureInfo = new TextureInfo();
Vector3 specularFactor = KHR_materials_pbrSpecularGlossinessExtension.SPEC_FACTOR_DEFAULT;
double glossinessFactor = KHR_materials_pbrSpecularGlossinessExtension.GLOSS_FACTOR_DEFAULT;
TextureInfo specularGlossinessTextureInfo = new TextureInfo();
if (extensionToken != null)
{
#if DEBUG
// Broken on il2cpp. Don't ship debug DLLs there.
System.Diagnostics.Debug.WriteLine(extensionToken.Value.ToString());
System.Diagnostics.Debug.WriteLine(extensionToken.Value.Type);
#endif
JToken diffuseFactorToken = extensionToken.Value[DIFFUSE_FACTOR];
diffuseFactor = diffuseFactorToken != null ? diffuseFactorToken.DeserializeAsColor() : diffuseFactor;
diffuseTextureInfo = extensionToken.Value[DIFFUSE_TEXTURE].DeserializeAsTexture(root);
JToken specularFactorToken = extensionToken.Value[SPECULAR_FACTOR];
specularFactor = specularFactorToken != null ? specularFactorToken.DeserializeAsVector3() : specularFactor;
JToken glossinessFactorToken = extensionToken.Value[GLOSSINESS_FACTOR];
glossinessFactor = glossinessFactorToken != null ? glossinessFactorToken.DeserializeAsDouble() : glossinessFactor;
specularGlossinessTextureInfo = extensionToken.Value[SPECULAR_GLOSSINESS_TEXTURE].DeserializeAsTexture(root);
}
return new KHR_materials_pbrSpecularGlossinessExtension(diffuseFactor, diffuseTextureInfo, specularFactor, glossinessFactor, specularGlossinessTextureInfo);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2d8808686675fa540b28186541d0b196
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,81 @@
using System;
using GLTF.Extensions;
using Newtonsoft.Json.Linq;
using Color = GLTF.Math.Color;
namespace GLTF.Schema
{
// https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_specular/README.md
[Serializable]
public class KHR_materials_specular : IExtension
{
public float specularFactor = 1f;
public TextureInfo specularTexture; // A channel
public Color specularColorFactor = COLOR_DEFAULT;
public TextureInfo specularColorTexture; // RGB channel
public static readonly Color COLOR_DEFAULT = Color.White;
public JProperty Serialize()
{
var jo = new JObject();
JProperty jProperty = new JProperty(KHR_materials_specular_Factory.EXTENSION_NAME, jo);
if (specularFactor != 1) jo.Add(new JProperty(nameof(specularFactor), specularFactor));
if (specularColorFactor != COLOR_DEFAULT) jo.Add(new JProperty(nameof(specularColorFactor), new JArray(specularColorFactor.R, specularColorFactor.G, specularColorFactor.B)));
if (specularTexture != null) {
jo.Add(new JProperty(nameof(specularTexture),
new JObject(
new JProperty(TextureInfo.INDEX, specularTexture.Index.Id),
new JProperty(TextureInfo.TEXCOORD, specularTexture.TexCoord)
)
)
);
}
if (specularColorTexture != null) {
jo.Add(new JProperty(nameof(specularColorTexture),
new JObject(
new JProperty(TextureInfo.INDEX, specularColorTexture.Index.Id),
new JProperty(TextureInfo.TEXCOORD, specularColorTexture.TexCoord)
)
)
);
}
return jProperty;
}
public IExtension Clone(GLTFRoot root)
{
return new KHR_materials_specular()
{
specularFactor = specularFactor, specularTexture = specularTexture,
specularColorFactor = specularColorFactor, specularColorTexture = specularColorTexture,
};
}
}
public class KHR_materials_specular_Factory : ExtensionFactory
{
public const string EXTENSION_NAME = "KHR_materials_specular";
public KHR_materials_specular_Factory()
{
ExtensionName = EXTENSION_NAME;
}
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
{
if (extensionToken != null)
{
var extension = new KHR_materials_specular();
extension.specularFactor = extensionToken.Value[nameof(KHR_materials_specular.specularFactor)]?.Value<float>() ?? 1;
extension.specularColorFactor = extensionToken.Value[nameof(KHR_materials_specular.specularColorFactor)]?.DeserializeAsColor() ?? Color.White;
extension.specularTexture = extensionToken.Value[nameof(KHR_materials_specular.specularTexture)]?.DeserializeAsTexture(root);
extension.specularColorTexture = extensionToken.Value[nameof(KHR_materials_specular.specularColorTexture)]?.DeserializeAsTexture(root);
return extension;
}
return null;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: cd1a3f573b7b4639854c977d6826c9b2
timeCreated: 1653662141
@@ -0,0 +1,58 @@
using System;
using GLTF.Extensions;
using Newtonsoft.Json.Linq;
namespace GLTF.Schema
{
// https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_transmission
[Serializable]
public class KHR_materials_transmission : IExtension
{
public float transmissionFactor = 0.0f;
public TextureInfo transmissionTexture; // transmissionTexture // R channel
public JProperty Serialize()
{
var jo = new JObject();
if (transmissionFactor != 0) jo.Add(new JProperty(nameof(transmissionFactor), transmissionFactor));
if (transmissionTexture != null)
jo.Add(new JProperty(nameof(transmissionTexture),
new JObject(
new JProperty(TextureInfo.INDEX, transmissionTexture.Index.Id),
new JProperty(TextureInfo.TEXCOORD, transmissionTexture.TexCoord) // TODO don't write if default
)
)
);
JProperty jProperty = new JProperty(KHR_materials_transmission_Factory.EXTENSION_NAME, jo);
return jProperty;
}
public IExtension Clone(GLTFRoot root)
{
return new KHR_materials_transmission() { transmissionFactor = transmissionFactor, transmissionTexture = transmissionTexture };
}
}
public class KHR_materials_transmission_Factory : ExtensionFactory
{
public const string EXTENSION_NAME = "KHR_materials_transmission";
public KHR_materials_transmission_Factory()
{
ExtensionName = EXTENSION_NAME;
}
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
{
if (extensionToken != null)
{
var extension = new KHR_materials_transmission();
extension.transmissionFactor = extensionToken.Value[nameof(KHR_materials_transmission.transmissionFactor)]?.Value<float>() ?? 0;
extension.transmissionTexture = extensionToken.Value[nameof(KHR_materials_transmission.transmissionTexture)]?.DeserializeAsTexture(root);
return extension;
}
return null;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: ae9748bb15524941ba2cda5ed4d3dbb4
timeCreated: 1653603710
@@ -0,0 +1,38 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace GLTF.Schema
{
/// <summary>
/// This extension defines an unlit shading model for use in glTF 2.0 materials, as an alternative to the Physically Based Rendering (PBR) shading models provided by the core specification.
///
/// Spec can be found here:
/// https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
/// </summary>
public class KHR_MaterialsUnlitExtension : GLTFProperty, IExtension
{
public KHR_MaterialsUnlitExtension() { }
public KHR_MaterialsUnlitExtension(KHR_MaterialsUnlitExtension ext, GLTFRoot root) : base(ext, root) { }
public IExtension Clone(GLTFRoot gltfRoot)
{
return new KHR_MaterialsUnlitExtension(this, gltfRoot);
}
override public void Serialize(JsonWriter writer)
{
writer.WritePropertyName(KHR_MaterialsUnlitExtensionFactory.EXTENSION_NAME);
writer.WriteStartObject();
base.Serialize(writer);
writer.WriteEndObject();
}
public JProperty Serialize()
{
JTokenWriter writer = new JTokenWriter();
Serialize(writer);
return (JProperty)writer.Token;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ebec0fdc2a825ef4d8c526c0a5d8c0b1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,23 @@
using System;
using Newtonsoft.Json.Linq;
using GLTF.Math;
using Newtonsoft.Json;
using GLTF.Extensions;
namespace GLTF.Schema
{
public class KHR_MaterialsUnlitExtensionFactory : ExtensionFactory
{
public const string EXTENSION_NAME = "KHR_materials_unlit";
public KHR_MaterialsUnlitExtensionFactory()
{
ExtensionName = EXTENSION_NAME;
}
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
{
return new KHR_MaterialsUnlitExtension();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 15b8bb59cb9b65e4f92a9cf273cdcf8d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,80 @@
using System;
using GLTF.Extensions;
using Newtonsoft.Json.Linq;
using Color = GLTF.Math.Color;
namespace GLTF.Schema
{
// https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_volume
[Serializable]
public class KHR_materials_volume : IExtension
{
public float thicknessFactor = 0f;
public TextureInfo thicknessTexture;// thicknessTexture // G channel
public float attenuationDistance = float.PositiveInfinity;
public Color attenuationColor = new Color(1, 1, 1, 1);
public static readonly Color COLOR_DEFAULT = Color.White;
public JProperty Serialize()
{
var jo = new JObject();
JProperty jProperty = new JProperty(KHR_materials_volume_Factory.EXTENSION_NAME, jo);
if (thicknessFactor != 0) jo.Add(new JProperty(nameof(thicknessFactor), thicknessFactor));
if (!float.IsPositiveInfinity(attenuationDistance))
{
// 0 not allowed
if (!(attenuationDistance > 0))
attenuationDistance = 0.0001f;
jo.Add(new JProperty(nameof(attenuationDistance), attenuationDistance));
}
if (attenuationColor != COLOR_DEFAULT) jo.Add(new JProperty(nameof(attenuationColor), new JArray(attenuationColor.R, attenuationColor.G, attenuationColor.B)));
if (thicknessTexture != null) {
jo.Add(new JProperty(nameof(thicknessTexture),
new JObject(
new JProperty(TextureInfo.INDEX, thicknessTexture.Index.Id),
new JProperty(TextureInfo.TEXCOORD, thicknessTexture.TexCoord) // TODO don't write if default
)
)
);
}
return jProperty;
}
public IExtension Clone(GLTFRoot root)
{
return new KHR_materials_volume()
{
thicknessFactor = thicknessFactor, attenuationDistance = attenuationDistance,
attenuationColor = attenuationColor, thicknessTexture = thicknessTexture,
};
}
}
public class KHR_materials_volume_Factory : ExtensionFactory
{
public const string EXTENSION_NAME = "KHR_materials_volume";
public KHR_materials_volume_Factory()
{
ExtensionName = EXTENSION_NAME;
}
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
{
if (extensionToken != null)
{
var extension = new KHR_materials_volume();
extension.thicknessFactor = extensionToken.Value[nameof(KHR_materials_volume.thicknessFactor)]?.Value<float>() ?? 0;
extension.attenuationColor = extensionToken.Value[nameof(KHR_materials_volume.attenuationColor)]?.DeserializeAsColor() ?? Color.White;
extension.attenuationDistance = extensionToken.Value[nameof(KHR_materials_volume.attenuationDistance)]?.Value<float>() ?? float.PositiveInfinity;
extension.thicknessTexture = extensionToken.Value[nameof(KHR_materials_volume.thicknessTexture)]?.DeserializeAsTexture(root);
return extension;
}
return null;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 6581bef44e7949e1ae7cf4a597183d1d
timeCreated: 1653603693
@@ -0,0 +1,47 @@
using GLTF.Extensions;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace GLTF.Schema
{
/// <summary>
/// glTF extension that defines the LOD
/// </summary>
public class MSFT_LODExtension : IExtension
{
public List<int> NodeIds { get; set; }
public MSFT_LODExtension(List<int> nodeIds)
{
NodeIds = nodeIds;
}
public IExtension Clone(GLTFRoot gltfRoot)
{
return new MSFT_LODExtension(NodeIds);
}
public JProperty Serialize()
{
JProperty jProperty = new JProperty(MSFT_LODExtensionFactory.EXTENSION_NAME,
new JObject(
new JProperty(MSFT_LODExtensionFactory.IDS, new JArray(NodeIds))
)
);
return jProperty;
}
public List<double> GetLODCoverage(Node node)
{
List<double> lodCoverage = null;
if (node.Extras != null)
{
JToken screenCoverageExtras = node.Extras[MSFT_LODExtensionFactory.SCREEN_COVERAGE_EXTRAS];
if (screenCoverageExtras != null)
{
lodCoverage = screenCoverageExtras.CreateReader().ReadDoubleList();
}
}
return lodCoverage;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5414556e16dc4bc40bb228d17d86ddd8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,36 @@
using Newtonsoft.Json.Linq;
using GLTF.Extensions;
using System.Collections.Generic;
namespace GLTF.Schema
{
public class MSFT_LODExtensionFactory : ExtensionFactory
{
public const string EXTENSION_NAME = "MSFT_lod";
public const string SCREEN_COVERAGE_EXTRAS = "MSFT_screencoverage";
public const string IDS = "ids";
public MSFT_LODExtensionFactory()
{
ExtensionName = EXTENSION_NAME;
}
public override IExtension Deserialize(GLTFRoot root, JProperty extensionToken)
{
List<int> meshIds = new List<int>();
if (extensionToken != null)
{
#if DEBUG
// Broken on il2cpp. Don't ship debug DLLs there.
System.Diagnostics.Debug.WriteLine(extensionToken.Value.ToString());
System.Diagnostics.Debug.WriteLine(extensionToken.Value.Type);
#endif
JToken meshIdsToken = extensionToken.Value[IDS];
meshIds = meshIdsToken.CreateReader().ReadInt32List();
}
return new MSFT_LODExtension(meshIds);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 879b237aa98612d468a9d18e34c9e9c1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,538 @@
using GLTF;
using GLTF.Schema;
using GLTF.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace GLTF
{
// Static class for construction GLB objects. These API's only work with the .NET 4.6 runtime and above.
public static class GLBBuilder
{
/// <summary>
/// Turns a glTF file w/ structure into a GLB. Does not currently copy binary data
/// </summary>
/// <param name="root">The glTF root to turn into a GLBObject</param>
/// <param name="glbOutStream">Output stream to write the GLB to</param>
/// <param name="loader">Loader for loading external components from GLTFRoot. The loader will receive uris and return the stream to the resource</param>
/// <returns>A constructed GLBObject</returns>
private static GLBObject ConstructFromGLTF(GLTFRoot root, Stream glbOutStream, Func<string, Stream> loader)
{
if (root == null) throw new ArgumentNullException(nameof(root));
if (glbOutStream == null) throw new ArgumentNullException(nameof(glbOutStream));
MemoryStream gltfJsonStream = new MemoryStream();
using (StreamWriter sw = new StreamWriter(gltfJsonStream))
{
root.Serialize(sw, true);
sw.Flush();
long proposedLength = gltfJsonStream.Length + GLTFParser.HEADER_SIZE + GLTFParser.CHUNK_HEADER_SIZE;
if (gltfJsonStream.Length > uint.MaxValue)
{
throw new ArgumentException("Serialized root cannot exceed uint.maxvalue", nameof(root));
}
uint proposedLengthAsUint = (uint)proposedLength;
glbOutStream.SetLength(proposedLengthAsUint);
GLBObject glbObject = new GLBObject
{
Header = new GLBHeader
{
FileLength = proposedLengthAsUint,
Version = 2
},
Root = root,
Stream = glbOutStream,
JsonChunkInfo = new ChunkInfo
{
Length = (uint)gltfJsonStream.Length,
StartPosition = GLTFParser.HEADER_SIZE,
Type = ChunkFormat.JSON
}
};
// write header
WriteHeader(glbOutStream, glbObject.Header, glbObject.StreamStartPosition);
// write chunk header
WriteChunkHeader(glbOutStream, glbObject.JsonChunkInfo);
gltfJsonStream.Position = 0;
gltfJsonStream.CopyTo(glbOutStream);
// todo: implement getting binary data for loader
return glbObject;
}
}
/// <summary>
/// Turns the GLB data contained in a stream into a GLBObject. Will copy to the outStream if specified
/// </summary>
/// <param name="root">The glTF root to turn into a GLBObject</param>
/// <param name="inputGLBStream">The stream the glb came in</param>
/// <param name="outStream">If outstream is specified, the glb gets copied to it</param>
/// <param name="inputGLBStreamStartPosition">Offset into the buffer that the GLB starts</param>
/// <returns>A constructed GLBObject</returns>
public static GLBObject ConstructFromGLB(GLTFRoot root, Stream inputGLBStream, Stream outStream = null,
long inputGLBStreamStartPosition = 0)
{
if (outStream != null)
{
inputGLBStream.Position = inputGLBStreamStartPosition;
inputGLBStream.CopyTo(outStream);
}
else
{
outStream = inputGLBStream;
}
// header information is 4 bytes in, past the magic number
inputGLBStream.Position = 4 + inputGLBStreamStartPosition;
GLBHeader header = GLTFParser.ParseGLBHeader(inputGLBStream);
inputGLBStream.Position = GLTFParser.HEADER_SIZE + inputGLBStreamStartPosition;
List<ChunkInfo> allChunks = GLTFParser.FindChunks(inputGLBStream);
ChunkInfo jsonChunkInfo = new ChunkInfo
{
Type = ChunkFormat.JSON
};
ChunkInfo binaryChunkInfo = new ChunkInfo
{
Type = ChunkFormat.BIN
};
foreach (ChunkInfo chunkInfo in allChunks)
{
switch (chunkInfo.Type)
{
case ChunkFormat.JSON:
jsonChunkInfo = chunkInfo;
break;
case ChunkFormat.BIN:
binaryChunkInfo = chunkInfo;
break;
}
}
if (jsonChunkInfo.Length == 0)
{
throw new ArgumentException("JSON chunk must exists for valid GLB", nameof(inputGLBStream));
}
// todo: compute the initial bufferview list
return new GLBObject
{
Root = root,
Stream = outStream,
StreamStartPosition = inputGLBStreamStartPosition,
Header = header,
JsonChunkInfo = jsonChunkInfo,
BinaryChunkInfo = binaryChunkInfo
};
}
/// <summary>
/// Turns a stream that contains glTF or a GLB data into a GLBObject. glTF is not yet supported
/// </summary>
/// <param name="inStream">The stream to turn into a GLB</param>
/// <param name="glbOutStream">If specified, output stream to write the GLB to</param>
/// <param name="loader">Loader for loading external components from GLTFRoot. Loader is required if loading from glTF</param>
/// <returns>A constructed GLBObject</returns>
public static GLBObject ConstructFromStream(Stream inStream, Stream glbOutStream = null, Func<string, Stream> loader = null,
long streamStartPosition = 0, bool removeUndefinedReferences = true)
{
if (inStream == null) throw new ArgumentNullException(nameof(inStream));
if (inStream.Length > 0)
{
inStream.Position = streamStartPosition;
GLTFRoot root;
GLTFParser.ParseJson(inStream, out root, streamStartPosition);
if (removeUndefinedReferences)
{
GLTFHelpers.RemoveUndefinedReferences(root);
}
if (!root.IsGLB)
{
return ConstructFromGLTF(root, glbOutStream, loader);
}
return ConstructFromGLB(root, inStream, glbOutStream, streamStartPosition);
}
return _ConstructFromEmptyStream(inStream, streamStartPosition);
}
private static GLBObject _ConstructFromEmptyStream(Stream inStream, long streamStartPosition)
{
GLBObject glbObject = new GLBObject
{
Stream = inStream,
JsonChunkInfo = new ChunkInfo
{
Length = 0,
StartPosition = GLTFParser.HEADER_SIZE,
Type = ChunkFormat.JSON
},
BinaryChunkInfo = new ChunkInfo
{
Length = 0,
StartPosition = GLTFParser.HEADER_SIZE + GLTFParser.CHUNK_HEADER_SIZE,
Type = ChunkFormat.BIN
},
Header = new GLBHeader
{
FileLength = GLTFParser.HEADER_SIZE,
Version = 2
},
StreamStartPosition = streamStartPosition
};
return glbObject;
}
/// <summary>
/// Saves out the GLBObject to its own stream
/// The GLBObject stream will be updated to be the output stream. Callers are reponsible for handling Stream lifetime
/// </summary>
/// <param name="glb">The GLB to flush to the output stream and update</param>
/// <param name="newRoot">Optional root to replace the one in the glb</param>
/// <returns>A GLBObject that is based upon outStream</returns>
public static void UpdateStream(GLBObject glb)
{
if (glb.Root == null) throw new ArgumentException("glb Root and newRoot cannot be null", nameof(glb.Root));
if (glb.Stream == null) throw new ArgumentException("glb GLBStream property cannot be null", nameof(glb.Stream));
MemoryStream gltfJsonStream = new MemoryStream();
using (StreamWriter sw = new StreamWriter(gltfJsonStream))
{
glb.Root.Serialize(sw, true); // todo: this could out of memory exception
sw.Flush();
if (gltfJsonStream.Length > int.MaxValue)
{
// todo: make this a non generic exception
throw new Exception("JSON chunk of GLB has exceeded maximum allowed size (4 GB)");
}
// realloc of out of space
if (glb.JsonChunkInfo.Length < gltfJsonStream.Length)
{
uint proposedJsonChunkLength = (uint)System.Math.Min((long)gltfJsonStream.Length * 2, uint.MaxValue); // allocate double what is required
proposedJsonChunkLength = CalculateAlignment(proposedJsonChunkLength, 4);
// chunks must be 4 byte aligned
uint amountToAddToFile = proposedJsonChunkLength - glb.JsonChunkInfo.Length;
// we have not yet initialized a json chunk before
if (glb.JsonChunkInfo.Length == 0)
{
amountToAddToFile += GLTFParser.CHUNK_HEADER_SIZE;
glb.SetJsonChunkStartPosition(GLTFParser.HEADER_SIZE);
}
// new proposed length = propsoedJsonBufferSize - currentJsonBufferSize + totalFileLength
long proposedLength = amountToAddToFile + glb.Header.FileLength;
if (proposedLength > uint.MaxValue)
{
throw new Exception("GLB has exceeded max allowed size (4 GB)");
}
uint proposedLengthAsUint = (uint)proposedLength;
try
{
glb.Stream.SetLength(proposedLength);
}
catch (IOException e)
{
#if WINDOWS_UWP
Debug.WriteLine(e);
#else
Console.WriteLine(e);
#endif
throw;
}
long newBinaryChunkStartPosition =
GLTFParser.HEADER_SIZE + GLTFParser.CHUNK_HEADER_SIZE + proposedJsonChunkLength;
glb.Stream.Position = glb.BinaryChunkInfo.StartPosition;
glb.SetBinaryChunkStartPosition(newBinaryChunkStartPosition);
if (glb.BinaryChunkInfo.Length > 0)
{
uint lengthToCopy = glb.BinaryChunkInfo.Length + GLTFParser.CHUNK_HEADER_SIZE;
// todo: we need to be able to copy while doing it with smaller buffers. Also int is smaller than uint, so this is not standards compliant.
glb.Stream.CopyToSelf((int)newBinaryChunkStartPosition,
lengthToCopy);
}
// write out new GLB length
glb.SetFileLength(proposedLengthAsUint);
WriteHeader(glb.Stream, glb.Header, glb.StreamStartPosition);
// write out new JSON header
glb.SetJsonChunkLength(proposedJsonChunkLength);
WriteChunkHeader(glb.Stream, glb.JsonChunkInfo);
}
// clear the buffer
glb.Stream.Position = glb.JsonChunkInfo.StartPosition + GLTFParser.CHUNK_HEADER_SIZE;
uint amountToCopy = glb.JsonChunkInfo.Length;
while (amountToCopy != 0)
{
int currAmountToCopy = (int)System.Math.Min(amountToCopy, int.MaxValue);
byte[] filler =
Encoding.ASCII.GetBytes(new string(' ', currAmountToCopy));
glb.Stream.Write(filler, 0, filler.Length);
amountToCopy -= (uint)currAmountToCopy;
}
// write new JSON data
gltfJsonStream.Position = 0;
glb.Stream.Position = glb.JsonChunkInfo.StartPosition + GLTFParser.CHUNK_HEADER_SIZE;
gltfJsonStream.CopyTo(glb.Stream);
glb.Stream.Flush();
}
}
/// <summary>
/// Adds binary data to the GLB
/// </summary>
/// <param name="glb">The glb to update</param>
/// <param name="binaryData">The binary data to append</param>
/// <param name="createBufferView">Whether a buffer view should be created, added to the GLTFRoot, and id returned</param>
/// <param name="streamStartPosition">Start position of stream</param>
/// <param name="bufferViewName">Root to replace the current one with</param>
/// <returns>The location of the added buffer view</returns>
public static BufferViewId AddBinaryData(GLBObject glb, Stream binaryData, bool createBufferView = true, long streamStartPosition = 0, string bufferViewName = null)
{
if (glb == null) throw new ArgumentNullException(nameof(glb));
if(glb.Root == null && bufferViewName == null) throw new ArgumentException("glb Root and new root cannot be null", nameof(glb));
if(glb.Stream == null) throw new ArgumentException("glb Stream cannot be null", nameof(glb));
if(binaryData == null) throw new ArgumentNullException(nameof(binaryData));
if(binaryData.Length > uint.MaxValue) throw new ArgumentException("Stream cannot be larger than uint.MaxValue", nameof(binaryData));
return _AddBinaryData(glb, binaryData, createBufferView, streamStartPosition, bufferViewName);
}
private static BufferViewId _AddBinaryData(GLBObject glb, Stream binaryData, bool createBufferView, long streamStartPosition, string bufferViewName = null)
{
binaryData.Position = streamStartPosition;
// Append new binary chunk to end
uint blobLengthAsUInt = CalculateAlignment((uint)(binaryData.Length - streamStartPosition), 4);
uint newBinaryBufferSize = glb.BinaryChunkInfo.Length + blobLengthAsUInt;
uint newGLBSize = glb.Header.FileLength + blobLengthAsUInt;
uint blobWritePosition = glb.Header.FileLength;
// there was an existing file that had no binary chunk info previously
if (glb.BinaryChunkInfo.Length == 0)
{
newGLBSize += GLTFParser.CHUNK_HEADER_SIZE;
blobWritePosition += GLTFParser.CHUNK_HEADER_SIZE;
glb.SetBinaryChunkStartPosition(glb.Header.FileLength); // if 0, then appends chunk info at the end
}
glb.Stream.SetLength(glb.Header.FileLength + blobLengthAsUInt);
glb.Stream.Position = blobWritePosition; // assuming the end of the file is the end of the binary chunk
binaryData.CopyTo(glb.Stream); // make sure this doesn't supersize it
glb.SetFileLength(newGLBSize);
glb.SetBinaryChunkLength(newBinaryBufferSize);
// write glb header past magic number
WriteHeader(glb.Stream, glb.Header, glb.StreamStartPosition);
WriteChunkHeader(glb.Stream, glb.BinaryChunkInfo);
if (createBufferView)
{
// Add a new BufferView to the GLTFRoot
BufferView bufferView = new BufferView
{
Buffer = new BufferId
{
Id = 0,
Root = glb.Root
},
ByteLength = blobLengthAsUInt, // figure out whether glb size is wrong or if documentation is unclear
ByteOffset = glb.BinaryChunkInfo.Length - blobLengthAsUInt,
Name = bufferViewName
};
if (glb.Root.BufferViews == null)
{
glb.Root.BufferViews = new List<BufferView>();
}
glb.Root.BufferViews.Add(bufferView);
return new BufferViewId
{
Id = glb.Root.BufferViews.Count - 1,
Root = glb.Root
};
}
return null;
}
/// <summary>
/// Merges two glb files together
/// </summary>
/// <param name="mergeTo">The glb to update</param>
/// <param name="mergeFrom">The glb to merge from</param>
public static void MergeGLBs(GLBObject mergeTo, GLBObject mergeFrom)
{
if (mergeTo == null) throw new ArgumentNullException(nameof(mergeTo));
if (mergeFrom == null) throw new ArgumentNullException(nameof(mergeFrom));
// 1) merge json
// 2) copy mergefrom binary data to mergeto binary data
// 3) Fix up bufferviews to be the new offset
int previousBufferViewsCount = mergeTo.Root.BufferViews?.Count ?? 0;
uint previousBufferSize = mergeTo.BinaryChunkInfo.Length;
GLTFHelpers.MergeGLTF(mergeTo.Root, mergeFrom.Root);
_AddBinaryData(mergeTo, mergeFrom.Stream, false, mergeFrom.BinaryChunkInfo.StartPosition + GLTFParser.CHUNK_HEADER_SIZE);
uint bufferSizeDiff =
mergeTo.BinaryChunkInfo.Length -
previousBufferSize; // calculate buffer size change to update the byte offsets of the appended buffer views
if (mergeTo.Root.BufferViews != null)
{
for (int i = previousBufferViewsCount; i < mergeTo.Root.BufferViews.Count; ++i)
{
mergeTo.Root.BufferViews[i].ByteOffset += bufferSizeDiff;
}
}
}
/// <summary>
/// Removes a blob from the GLB at the given BufferView
/// Updates accessors and images to have correct new bufferview index
/// This function can invalidate BufferViewId's returned by previous function
/// </summary>
/// <param name="glb">The glb to remove from</param>
/// <param name="bufferViewId">The buffer to remove</param>
public static void RemoveBinaryData(GLBObject glb, BufferViewId bufferViewId)
{
if (glb == null) throw new ArgumentNullException(nameof(glb));
if (bufferViewId == null) throw new ArgumentNullException(nameof(bufferViewId));
BufferView bufferViewToRemove = bufferViewId.Value;
int id = bufferViewId.Id;
if (bufferViewToRemove.ByteOffset + bufferViewToRemove.ByteLength == glb.BinaryChunkInfo.Length)
{
uint bufferViewLengthAsUint = bufferViewToRemove.ByteLength;
glb.SetFileLength(glb.Header.FileLength - bufferViewLengthAsUint);
glb.SetBinaryChunkLength(glb.BinaryChunkInfo.Length - bufferViewLengthAsUint);
if (glb.BinaryChunkInfo.Length == 0)
{
glb.Root.Buffers.RemoveAt(0);
foreach (BufferView bufferView in glb.Root.BufferViews) // other buffers may still exist, and their index has now changed
{
--bufferView.Buffer.Id;
}
glb.SetFileLength(glb.Header.FileLength - GLTFParser.CHUNK_HEADER_SIZE);
}
else
{
glb.Root.Buffers[0].ByteLength = glb.BinaryChunkInfo.Length;
// write binary chunk header
WriteChunkHeader(glb.Stream, glb.BinaryChunkInfo);
}
// trim the end
glb.Stream.SetLength(glb.Header.FileLength);
// write glb header
WriteHeader(glb.Stream, glb.Header, glb.StreamStartPosition);
}
glb.Root.BufferViews.RemoveAt(id);
if (glb.Root.Accessors != null)
{
foreach (Accessor accessor in glb.Root.Accessors) // shift over all accessors
{
if (accessor.BufferView != null && accessor.BufferView.Id >= id)
{
--accessor.BufferView.Id;
}
if (accessor.Sparse != null)
{
if (accessor.Sparse.Indices?.BufferView.Id >= id)
{
--accessor.Sparse.Indices.BufferView.Id;
}
if (accessor.Sparse.Values?.BufferView.Id >= id)
{
--accessor.Sparse.Values.BufferView.Id;
}
}
}
}
if (glb.Root.Images != null)
{
foreach (GLTFImage image in glb.Root.Images)
{
if (image.BufferView != null && image.BufferView.Id >= id)
{
--image.BufferView.Id;
}
}
}
}
/// <summary>
/// Added function to set the root
/// </summary>
/// <param name="glb">GLB to add</param>
/// <param name="newRoot">The new root to update it with</param>
public static void SetRoot(GLBObject glb, GLTFRoot newRoot)
{
if (newRoot != null)
{
glb.Root = newRoot;
}
}
private static void WriteHeader(Stream stream, GLBHeader header, long streamStartPosition)
{
stream.Position = streamStartPosition;
byte[] magicNumber = BitConverter.GetBytes(GLTFParser.MAGIC_NUMBER);
byte[] version = BitConverter.GetBytes(header.Version);
byte[] length = BitConverter.GetBytes(header.FileLength);
stream.Write(magicNumber, 0, magicNumber.Length);
stream.Write(version, 0, version.Length);
stream.Write(length, 0, length.Length);
}
private static void WriteChunkHeader(Stream stream, ChunkInfo chunkInfo)
{
stream.Position = chunkInfo.StartPosition;
byte[] lengthBytes = BitConverter.GetBytes(chunkInfo.Length);
byte[] typeBytes = BitConverter.GetBytes((uint)chunkInfo.Type);
stream.Write(lengthBytes, 0, lengthBytes.Length);
stream.Write(typeBytes, 0, lengthBytes.Length);
}
public static uint CalculateAlignment(uint currentSize, uint byteAlignment)
{
return (currentSize + byteAlignment - 1) / byteAlignment * byteAlignment;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1ff8d4b6beb2ca648926a7f0e032a63e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,101 @@
using GLTF.Schema;
using System.Collections.Generic;
using System.IO;
namespace GLTF
{
/// <summary>
/// Objects containing GLB data and associated parsing information
/// </summary>
public class GLBObject : IGLTFObject
{
public GLBObject(GLBObject other)
{
Root = other.Root;
Header = other.Header;
StreamStartPosition = other.StreamStartPosition;
JsonChunkInfo = other.JsonChunkInfo;
BinaryChunkInfo = other.BinaryChunkInfo;
}
/// <summary>
/// Parsed JSON of the GLB
/// </summary>
public GLTFRoot Root { get; internal set; }
/// <summary>
/// Read/Write Stream that GLB exists in
/// </summary>
public Stream Stream { get; set; }
/// <summary>
/// Header of GLB
/// </summary>
public GLBHeader Header { get { return _glbHeader; } internal set { _glbHeader = value; } }
/// <summary>
/// Start position for the GLB stream
/// </summary>
public long StreamStartPosition { get; internal set; }
/// <summary>
/// Information on JSON chunk
/// </summary>
public ChunkInfo JsonChunkInfo { get { return _jsonChunkInfo; } internal set { _jsonChunkInfo = value; } }
/// <summary>
/// Information on Binary chunk
/// </summary>
public ChunkInfo BinaryChunkInfo { get { return _binaryChunkInfo; } internal set { _binaryChunkInfo = value; } }
private GLBHeader _glbHeader;
private ChunkInfo _jsonChunkInfo;
private ChunkInfo _binaryChunkInfo;
internal GLBObject()
{
}
internal void SetFileLength(uint newHeaderLength)
{
_glbHeader.FileLength = newHeaderLength;
}
internal void SetJsonChunkStartPosition(long startPosition)
{
_jsonChunkInfo.StartPosition = startPosition;
}
internal void SetJsonChunkLength(uint jsonChunkLength)
{
_jsonChunkInfo.Length = jsonChunkLength;
}
internal void SetBinaryChunkStartPosition(long startPosition)
{
_binaryChunkInfo.StartPosition = startPosition;
}
internal void SetBinaryChunkLength(uint binaryChunkLength)
{
_binaryChunkInfo.Length = binaryChunkLength;
if (Root.Buffers == null)
{
Root.Buffers = new List<GLTFBuffer>();
}
if (Root.Buffers.Count == 0)
{
Root.Buffers.Add(new GLTFBuffer
{
ByteLength = binaryChunkLength
});
}
else
{
Root.Buffers[0].ByteLength = binaryChunkLength;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2ddfd4d551e573949a2644728ae031bc
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: 263666854cbd1bc489267c0f2112f5e1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,20 @@
using GLTF.Schema;
namespace GLTF
{
/// <summary>
/// Represents a glTF file (specifically not GLB)
/// </summary>
public class GLTFObject : IGLTFObject
{
public GLTFObject(GLTFRoot root)
{
Root = root;
}
/// <summary>
/// Parsed glTF into a strongly typed C# object
/// </summary>
public GLTFRoot Root { get; internal set; }
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0a76e06d7bdb61347a2118c05b86c181
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,175 @@
using GLTF.Schema;
using System;
using System.Collections.Generic;
using System.IO;
namespace GLTF
{
public enum ChunkFormat : uint
{
JSON = 0x4e4f534a,
BIN = 0x004e4942
}
/// <summary>
/// Information containing parsed GLB Header
/// </summary>
public struct GLBHeader
{
public uint Version { get; set; }
public uint FileLength { get; set; }
}
/// <summary>
/// Infomration that contains parsed chunk
/// </summary>
public struct ChunkInfo
{
public long StartPosition;
public uint Length;
public ChunkFormat Type;
}
public class GLTFParser
{
public static readonly uint HEADER_SIZE = 12;
public static readonly uint CHUNK_HEADER_SIZE = 8;
public static readonly uint MAGIC_NUMBER = 0x46546c67;
public static void ParseJson(Stream stream, out GLTFRoot gltfRoot, long startPosition = 0)
{
stream.Position = startPosition;
bool isGLB = IsGLB(stream);
// Check for binary format magic bytes
if (isGLB)
{
ParseJsonChunk(stream, startPosition);
}
else
{
stream.Position = startPosition;
}
gltfRoot = GLTFRoot.Deserialize(new StreamReader(stream));
gltfRoot.IsGLB = isGLB;
}
// todo: this needs reimplemented. There is no such thing as a binary chunk index, and the chunk may not be in 0, 1, 2 order
// Moves stream position to binary chunk location
public static ChunkInfo SeekToBinaryChunk(Stream stream, int binaryChunkIndex, long startPosition = 0)
{
stream.Position = startPosition + 4; // start after magic number chunk
GLBHeader header = ParseGLBHeader(stream);
uint chunkOffset = 12; // sizeof(GLBHeader) + magic number
uint chunkLength = 0;
for (int i = 0; i < binaryChunkIndex + 2; ++i)
{
chunkOffset += chunkLength;
stream.Position = chunkOffset;
chunkLength = GetUInt32(stream);
chunkOffset += 8; // to account for chunk length (4 bytes) and type (4 bytes)
}
// Load Binary Chunk
if (chunkOffset + chunkLength <= header.FileLength)
{
ChunkFormat chunkType = (ChunkFormat)GetUInt32(stream);
if (chunkType != ChunkFormat.BIN)
{
throw new GLTFHeaderInvalidException("Second chunk must be of type BIN if present");
}
return new ChunkInfo
{
StartPosition = stream.Position - CHUNK_HEADER_SIZE,
Length = chunkLength,
Type = chunkType
};
}
throw new GLTFHeaderInvalidException("File length does not match chunk header.");
}
public static GLBHeader ParseGLBHeader(Stream stream)
{
uint version = GetUInt32(stream); // 4
uint length = GetUInt32(stream); // 8
return new GLBHeader
{
Version = version,
FileLength = length
};
}
public static bool IsGLB(Stream stream)
{
return GetUInt32(stream) == 0x46546c67; // 0
}
public static ChunkInfo ParseChunkInfo(Stream stream)
{
ChunkInfo chunkInfo = new ChunkInfo
{
StartPosition = stream.Position
};
chunkInfo.Length = GetUInt32(stream); // 12
chunkInfo.Type = (ChunkFormat)GetUInt32(stream); // 16
return chunkInfo;
}
public static List<ChunkInfo> FindChunks(Stream stream, long startPosition = 0)
{
stream.Position = startPosition + 4; // start after magic number bytes (4 bytes past)
ParseGLBHeader(stream);
List<ChunkInfo> allChunks = new List<ChunkInfo>();
// we only need to search for top two chunks (the JSON and binary chunks are guarenteed to be the top two chunks)
// other chunks can be in the file but we do not care about them
for (int i = 0; i < 2; ++i)
{
if (stream.Position == stream.Length)
{
break;
}
ChunkInfo chunkInfo = ParseChunkInfo(stream);
allChunks.Add(chunkInfo);
stream.Position += chunkInfo.Length;
}
return allChunks;
}
private static void ParseJsonChunk(Stream stream, long startPosition)
{
GLBHeader header = ParseGLBHeader(stream); // 4, 8
if (header.Version != 2)
{
throw new GLTFHeaderInvalidException("Unsupported glTF version");
};
if (header.FileLength > (stream.Length - startPosition))
{
throw new GLTFHeaderInvalidException("File length does not match header.");
}
ChunkInfo chunkInfo = ParseChunkInfo(stream);
if (chunkInfo.Type != ChunkFormat.JSON)
{
throw new GLTFHeaderInvalidException("First chunk must be of type JSON");
}
}
private static uint GetUInt32(Stream stream)
{
var uintSize = sizeof(uint);
byte[] headerBuffer = new byte[uintSize];
stream.Read(headerBuffer, 0, uintSize);
return BitConverter.ToUInt32(headerBuffer, 0);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6baa61f5385e65042bc17abb85d5f9b4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,16 @@
{
"name": "GLTFSerialization",
"rootNamespace": "",
"references": [],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": true,
"precompiledReferences": [
"Newtonsoft.Json.dll"
],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": true
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 40f39bff7bc9be34182ebe488fcf8228
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,12 @@
using GLTF.Schema;
namespace GLTF
{
/// <summary>
/// Represents a GLTFObject
/// </summary>
public interface IGLTFObject
{
GLTFRoot Root { get; }
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5d3d653bfec13be4c9e06a22631d3420
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 0833101f3e32c5849a37072f628efc15
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: cde5e1bb32bb63047be2e7ef338ffd50
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,65 @@
using System;
namespace GLTF.Math
{
public struct Color : IEquatable<Color>
{
public static Color Black { get { return new Color(0f, 0f, 0f, 1f); } }
public static Color Clear { get { return new Color(0f, 0f, 0f, 0f); } }
public static Color White { get { return new Color(1f, 1f, 1f, 1f); } }
public float R { get; set; }
public float G { get; set; }
public float B { get; set; }
public float A { get; set; }
public Color(float r, float g, float b, float a)
{
R = r;
G = g;
B = b;
A = a;
}
public Color(Color other)
{
R = other.R;
G = other.G;
B = other.B;
A = other.A;
}
public bool Equals(Color other)
{
return R.Equals(other.R) && G.Equals(other.G) && B.Equals(other.B) && A.Equals(other.A);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Color && Equals((Color) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = R.GetHashCode();
hashCode = (hashCode * 397) ^ G.GetHashCode();
hashCode = (hashCode * 397) ^ B.GetHashCode();
hashCode = (hashCode * 397) ^ A.GetHashCode();
return hashCode;
}
}
public static bool operator ==(Color left, Color right)
{
return left.Equals(right);
}
public static bool operator !=(Color left, Color right)
{
return !left.Equals(right);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e7ba942550f634246ac9a798262e498f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,185 @@
using System;
namespace GLTF.Math
{
// class is naively implemented
public class Matrix4x4 : IEquatable<Matrix4x4>
{
public static readonly Matrix4x4 Identity = new Matrix4x4(
1f, 0f, 0f, 0f,
0f, 1f, 0f, 0f,
0f, 0f, 1f, 0f,
0f, 0f, 0f, 1f
);
/// <summary>
/// Matrix is column major ordered
/// </summary>
public Matrix4x4(float m11, float m21, float m31, float m41, float m12, float m22, float m32, float m42, float m13, float m23, float m33, float m43, float m14, float m24, float m34, float m44)
{
M11 = m11;
M12 = m12;
M13 = m13;
M14 = m14;
M21 = m21;
M22 = m22;
M23 = m23;
M24 = m24;
M31 = m31;
M32 = m32;
M33 = m33;
M34 = m34;
M41 = m41;
M42 = m42;
M43 = m43;
M44 = m44;
}
public Matrix4x4(Matrix4x4 other)
{
Array.Copy(other.mat, 0, mat, 0, 16);
}
private float[] mat = new float[16];
public float M11 { get { return mat[0]; } set { mat[0] = value; } }
public float M21 { get { return mat[1]; } set { mat[1] = value; } }
public float M31 { get { return mat[2]; } set { mat[2] = value; } }
public float M41 { get { return mat[3]; } set { mat[3] = value; } }
public float M12 { get { return mat[4]; } set { mat[4] = value; } }
public float M22 { get { return mat[5]; } set { mat[5] = value; } }
public float M32 { get { return mat[6]; } set { mat[6] = value; } }
public float M42 { get { return mat[7]; } set { mat[7] = value; } }
public float M13 { get { return mat[8]; } set { mat[8] = value; } }
public float M23 { get { return mat[9]; } set { mat[9] = value; } }
public float M33 { get { return mat[10]; } set { mat[10] = value; } }
public float M43 { get { return mat[11]; } set { mat[11] = value; } }
public float M14 { get { return mat[12]; } set { mat[12] = value; } }
public float M24 { get { return mat[13]; } set { mat[13] = value; } }
public float M34 { get { return mat[14]; } set { mat[14] = value; } }
public float M44 { get { return mat[15]; } set { mat[15] = value; } }
public bool Equals(Matrix4x4 other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return M11 == other.M11 && M12 == other.M12 && M13 == other.M13 && M14 == other.M14 &&
M21 == other.M21 && M22 == other.M22 && M23 == other.M23 && M24 == other.M24 &&
M31 == other.M31 && M32 == other.M32 && M33 == other.M33 && M34 == other.M34 &&
M41 == other.M41 && M42 == other.M42 && M43 == other.M43 && M44 == other.M44;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Matrix4x4) obj);
}
public override int GetHashCode()
{
return (mat != null ? mat.GetHashCode() : 0);
}
public void SetValue(int index, float value)
{
if(index > mat.Length)
{
throw new IndexOutOfRangeException("Index " + index + " is out of range for a 4x4 matrix.");
}
mat[index] = value;
}
public void SetValue(int row, int column, float value)
{
switch(row)
{
case 0:
switch (column)
{
case 0:
M11 = value;
break;
case 1:
M12 = value;
break;
case 2:
M13 = value;
break;
case 3:
M14 = value;
break;
default:
throw new IndexOutOfRangeException("Column " + column + " is out of range for a 4x4 matrix.");
}
break;
case 1:
switch (column)
{
case 0:
M21 = value;
break;
case 1:
M22 = value;
break;
case 2:
M23 = value;
break;
case 3:
M24 = value;
break;
default:
throw new IndexOutOfRangeException("Column " + column + " is out of range for a 4x4 matrix.");
}
break;
case 2:
switch (column)
{
case 0:
M31 = value;
break;
case 1:
M32 = value;
break;
case 2:
M33 = value;
break;
case 3:
M34 = value;
break;
default:
throw new IndexOutOfRangeException("Column " + column + " is out of range for a 4x4 matrix.");
}
break;
case 3:
switch (column)
{
case 0:
M41 = value;
break;
case 1:
M42 = value;
break;
case 2:
M43 = value;
break;
case 3:
M44 = value;
break;
default:
throw new IndexOutOfRangeException("Column " + column + " is out of range for a 4x4 matrix.");
}
break;
default:
throw new IndexOutOfRangeException("Row " + row + " is out of range for a 4x4 matrix.");
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9aeefcfaec31e2945bdd16285de33227
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,76 @@
using System;
namespace GLTF.Math
{
public struct Quaternion : IEquatable<Quaternion>
{
public static readonly Quaternion Identity = new Quaternion(0f, 0f, 0f, 1f);
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
public float W { get; set; }
public Quaternion(float x, float y, float z, float w)
{
X = x;
Y = y;
Z = z;
W = w;
}
public Quaternion(Quaternion other)
{
X = other.X;
Y = other.Y;
Z = other.Z;
W = other.W;
}
public bool Equals(Quaternion other)
{
return X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z) && W.Equals(other.W);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Quaternion && Equals((Quaternion) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = X.GetHashCode();
hashCode = (hashCode * 397) ^ Y.GetHashCode();
hashCode = (hashCode * 397) ^ Z.GetHashCode();
hashCode = (hashCode * 397) ^ W.GetHashCode();
return hashCode;
}
}
public static bool operator ==(Quaternion left, Quaternion right)
{
return left.Equals(right);
}
public static bool operator !=(Quaternion left, Quaternion right)
{
return !left.Equals(right);
}
/// First quaternion.
/// Second quaternion.
/// Result of multiplication.
public static Quaternion operator *(Quaternion left, Quaternion right)
{
float x = left.W * right.X + left.X * right.W + left.Y * right.Z - left.Z * right.Y;
float y = left.W * right.Y + left.Y * right.W + left.Z * right.X - left.X * right.Z;
float z = left.W * right.Z + left.Z * right.W + left.X * right.Y - left.Y * right.X;
float w = left.W * right.W - left.X * right.X - left.Y * right.Y - left.Z * right.Z;
Quaternion result = new Quaternion(x, y, z, w);
return result;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 21f2d9fe5dc7e3c4a873d2f2d5deb404
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,51 @@
using System;
namespace GLTF.Math
{
public struct Vector2 : IEquatable<Vector2>
{
public float X { get; set; }
public float Y { get; set; }
public Vector2(float x, float y)
{
X = x;
Y = y;
}
public Vector2(Vector2 other)
{
X = other.X;
Y = other.Y;
}
public bool Equals(Vector2 other)
{
return X.Equals(other.X) && Y.Equals(other.Y);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Vector2 && Equals((Vector2) obj);
}
public override int GetHashCode()
{
unchecked
{
return (X.GetHashCode() * 397) ^ Y.GetHashCode();
}
}
public static bool operator ==(Vector2 left, Vector2 right)
{
return left.Equals(right);
}
public static bool operator !=(Vector2 left, Vector2 right)
{
return !left.Equals(right);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1ce6455297f415343beeaaec7bddb32d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,61 @@
using System;
namespace GLTF.Math
{
public struct Vector3 : IEquatable<Vector3>
{
public static readonly Vector3 Zero = new Vector3(0f, 0f, 0f);
public static readonly Vector3 One = new Vector3(1f, 1f, 1f);
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
public Vector3(Vector3 other)
{
X = other.X;
Y = other.Y;
Z = other.Z;
}
public bool Equals(Vector3 other)
{
return X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Vector3 && Equals((Vector3) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = X.GetHashCode();
hashCode = (hashCode * 397) ^ Y.GetHashCode();
hashCode = (hashCode * 397) ^ Z.GetHashCode();
return hashCode;
}
}
public static bool operator ==(Vector3 left, Vector3 right)
{
return left.Equals(right);
}
public static bool operator !=(Vector3 left, Vector3 right)
{
return !left.Equals(right);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d1691a2a5c9edac418814a93b69b2f4b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,62 @@
using System;
namespace GLTF.Math
{
public struct Vector4 : IEquatable<Vector4>
{
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
public float W { get; set; }
public Vector4(float x, float y, float z, float w)
{
X = x;
Y = y;
Z = z;
W = w;
}
public Vector4(Vector4 other)
{
X = other.X;
Y = other.Y;
Z = other.Z;
W = other.W;
}
public bool Equals(Vector4 other)
{
return X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z) && W.Equals(other.W);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Vector4 && Equals((Vector4) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = X.GetHashCode();
hashCode = (hashCode * 397) ^ Y.GetHashCode();
hashCode = (hashCode * 397) ^ Z.GetHashCode();
hashCode = (hashCode * 397) ^ W.GetHashCode();
return hashCode;
}
}
public static bool operator ==(Vector4 left, Vector4 right)
{
return left.Equals(right);
}
public static bool operator !=(Vector4 left, Vector4 right)
{
return !left.Equals(right);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5da6fe3b49e1de94a9ced1f70dd1bf84
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 27196d12847e1f441b0b711ca2ce9ac4
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("GLTFSerialization")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GLTFSerializer")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("72AC331F-9810-4DE2-8EA3-84559A787218")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a9cfc1efa73335948afd6531e3a55ac1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: fc456dd013a8e964abdb43ca81d17b18
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,874 @@
using System;
using System.Collections.Generic;
using System.Linq;
using GLTF.Extensions;
using GLTF.Math;
using Newtonsoft.Json;
using System.Runtime.InteropServices;
using GLTF.Utilities;
namespace GLTF.Schema
{
public class Accessor : GLTFChildOfRootProperty
{
/// <summary>
/// The index of the bufferView.
/// If this is undefined, look in the sparse object for the index and value buffer views.
/// </summary>
public BufferViewId BufferView;
/// <summary>
/// The offset relative to the start of the bufferView in bytes.
/// This must be a multiple of the size of the component datatype.
/// <minimum>0</minimum>
/// </summary>
public uint ByteOffset;
/// <summary>
/// The datatype of components in the attribute.
/// All valid values correspond to WebGL enums.
/// The corresponding typed arrays are: `Int8Array`, `Uint8Array`, `Int16Array`,
/// `Uint16Array`, `Uint32Array`, and `Float32Array`, respectively.
/// 5125 (UNSIGNED_INT) is only allowed when the accessor contains indices
/// i.e., the accessor is only referenced by `primitive.indices`.
/// </summary>
public GLTFComponentType ComponentType;
/// <summary>
/// Specifies whether integer data values should be normalized
/// (`true`) to [0, 1] (for unsigned types) or [-1, 1] (for signed types),
/// or converted directly (`false`) when they are accessed.
/// Must be `false` when accessor is used for animation data.
/// </summary>
public bool Normalized;
/// <summary>
/// The number of attributes referenced by this accessor, not to be confused
/// with the number of bytes or number of components.
/// <minimum>1</minimum>
/// </summary>
public uint Count;
/// <summary>
/// Specifies if the attribute is a scalar, vector, or matrix,
/// and the number of elements in the vector or matrix.
/// </summary>
public GLTFAccessorAttributeType Type;
/// <summary>
/// Maximum value of each component in this attribute.
/// Both min and max arrays have the same length.
/// The length is determined by the value of the type property;
/// it can be 1, 2, 3, 4, 9, or 16.
///
/// When `componentType` is `5126` (FLOAT) each array value must be stored as
/// double-precision JSON number with numerical value which is equal to
/// buffer-stored single-precision value to avoid extra runtime conversions.
///
/// `normalized` property has no effect on array values: they always correspond
/// to the actual values stored in the buffer. When accessor is sparse, this
/// property must contain max values of accessor data with sparse substitution
/// applied.
/// <minItems>1</minItems>
/// <maxItems>16</maxItems>
/// </summary>
public List<double> Max;
/// <summary>
/// Minimum value of each component in this attribute.
/// Both min and max arrays have the same length. The length is determined by
/// the value of the type property; it can be 1, 2, 3, 4, 9, or 16.
///
/// When `componentType` is `5126` (FLOAT) each array value must be stored as
/// double-precision JSON number with numerical value which is equal to
/// buffer-stored single-precision value to avoid extra runtime conversions.
///
/// `normalized` property has no effect on array values: they always correspond
/// to the actual values stored in the buffer. When accessor is sparse, this
/// property must contain min values of accessor data with sparse substitution
/// applied.
/// <minItems>1</minItems>
/// <maxItems>16</maxItems>
/// </summary>
public List<double> Min;
/// <summary>
/// Sparse storage of attributes that deviate from their initialization value.
/// </summary>
public AccessorSparse Sparse;
public Accessor()
{
}
public Accessor(Accessor accessor, GLTFRoot gltfRoot) : base(accessor, gltfRoot)
{
if (accessor == null)
{
return;
}
if (accessor.BufferView != null)
{
BufferView = new BufferViewId(accessor.BufferView, gltfRoot);
}
ByteOffset = accessor.ByteOffset;
ComponentType = accessor.ComponentType;
Normalized = accessor.Normalized;
Count = accessor.Count;
Type = accessor.Type;
if (accessor.Max != null)
{
Max = accessor.Max.ToList();
}
if (accessor.Min != null)
{
Min = accessor.Min.ToList();
}
if (accessor.Sparse != null)
{
Sparse = new AccessorSparse(accessor.Sparse, gltfRoot);
}
}
public static Accessor Deserialize(GLTFRoot root, JsonReader reader)
{
var accessor = new Accessor();
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
{
var curProp = reader.Value.ToString();
switch (curProp)
{
case "bufferView":
accessor.BufferView = BufferViewId.Deserialize(root, reader);
break;
case "byteOffset":
accessor.ByteOffset = reader.ReadDoubleAsUInt32();
break;
case "componentType":
accessor.ComponentType = (GLTFComponentType)reader.ReadAsInt32().Value;
break;
case "normalized":
accessor.Normalized = reader.ReadAsBoolean().Value;
break;
case "count":
accessor.Count = reader.ReadDoubleAsUInt32();
break;
case "type":
accessor.Type = reader.ReadStringEnum<GLTFAccessorAttributeType>();
break;
case "max":
accessor.Max = reader.ReadDoubleList();
break;
case "min":
accessor.Min = reader.ReadDoubleList();
break;
case "sparse":
accessor.Sparse = AccessorSparse.Deserialize(root, reader);
break;
default:
accessor.DefaultPropertyDeserializer(root, reader);
break;
}
}
return accessor;
}
public override void Serialize(JsonWriter writer)
{
writer.WriteStartObject();
if (BufferView != null)
{
writer.WritePropertyName("bufferView");
writer.WriteValue(BufferView.Id);
}
if (ByteOffset != 0)
{
writer.WritePropertyName("byteOffset");
writer.WriteValue(ByteOffset);
}
writer.WritePropertyName("componentType");
writer.WriteValue(ComponentType);
if (Normalized != false)
{
writer.WritePropertyName("normalized");
writer.WriteValue(true);
}
writer.WritePropertyName("count");
writer.WriteValue(Count);
writer.WritePropertyName("type");
writer.WriteValue(Type.ToString());
bool isMaxNull = Max == null;
bool isMinNull = Min == null;
if (!isMaxNull)
{
writer.WritePropertyName("max");
writer.WriteStartArray();
foreach (var item in Max)
{
writer.WriteValue(item);
}
writer.WriteEndArray();
}
if (!isMinNull)
{
writer.WritePropertyName("min");
writer.WriteStartArray();
foreach (var item in Min)
{
writer.WriteValue(item);
}
writer.WriteEndArray();
}
if (Sparse != null)
{
if (isMinNull || isMaxNull)
{
throw new JsonSerializationException("Min and max attribute cannot be null when attribute is sparse");
}
writer.WritePropertyName("sparse");
Sparse.Serialize(writer);
}
base.Serialize(writer);
writer.WriteEndObject();
}
private static sbyte GetByteElement(byte[] buffer, uint byteOffset)
{
return Convert.ToSByte(GetUByteElement(buffer, byteOffset));
}
private static byte GetUByteElement(byte[] buffer, uint byteOffset)
{
return buffer[byteOffset]; // should only be byte size long
}
private static unsafe short GetShortElement(byte[] buffer, uint byteOffset)
{
fixed (byte* offsetBuffer = &buffer[byteOffset])
{
return *((short*)offsetBuffer);
}
}
private static unsafe ushort GetUShortElement(byte[] buffer, uint byteOffset)
{
fixed (byte* offsetBuffer = &buffer[byteOffset])
{
return *((ushort*)offsetBuffer);
}
}
private static unsafe uint GetUIntElement(byte[] buffer, uint byteOffset)
{
fixed (byte* offsetBuffer = &buffer[byteOffset])
{
return *((uint*)offsetBuffer);
}
}
private static unsafe float GetFloatElement(byte[] buffer, uint byteOffset)
{
fixed (byte* offsetBuffer = &buffer[byteOffset])
{
return *((float*)offsetBuffer);
}
}
public static GLTF.Math.Vector3[] AsSparseVector3Array(Accessor paraAccessor, ref NumericArray contents, byte[] bufferViewData, uint offset, bool normalizeIntValues = true)
{
var Count = paraAccessor.Sparse.Count;
var ComponentType = paraAccessor.ComponentType;
var arr = new GLTF.Math.Vector3[paraAccessor.Sparse.Count];
var totalByteOffset = (uint) paraAccessor.Sparse.Values.ByteOffset + offset;
uint componentSize;
float maxValue;
GetTypeDetails(paraAccessor.ComponentType, out componentSize, out maxValue);
uint stride = componentSize * 3;
if (normalizeIntValues) maxValue = 1;
for (uint idx = 0; idx < Count; idx++)
{
if (ComponentType == GLTFComponentType.Float)
{
arr[idx].X = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 0);
arr[idx].Y = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 1);
arr[idx].Z = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 2);
}
else
{
arr[idx].X = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 0, ComponentType) / maxValue;
arr[idx].Y = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 1, ComponentType) / maxValue;
arr[idx].Z = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 2, ComponentType) / maxValue;
}
}
contents.AsVec3s = arr;
return arr;
}
public static uint[] AsSparseUIntArray(Accessor paraAccessor, ref NumericArray contents, byte[] bufferViewData, uint offset)
{
var arr = new uint[paraAccessor.Sparse.Count];
var totalByteOffset = paraAccessor.Sparse.Indices.ByteOffset + offset;
uint componentSize;
float maxValue;
GetTypeDetails(paraAccessor.Sparse.Indices.ComponentType, out componentSize, out maxValue);
uint stride = componentSize;
for (uint idx = 0; idx < paraAccessor.Sparse.Count; idx++)
{
if (stride == 1)
{
arr[idx] = (uint)bufferViewData[(int)(totalByteOffset + idx)];
}
else
{
arr[idx] = System.BitConverter.ToUInt16(bufferViewData, (int)(totalByteOffset + idx * stride));
}
}
contents.AsUInts = arr;
return arr;
}
internal static void GetTypeDetails(
GLTFComponentType type,
out uint componentSize,
out float maxValue)
{
componentSize = 1;
maxValue = byte.MaxValue;
switch (type)
{
case GLTFComponentType.Byte:
componentSize = sizeof(sbyte);
maxValue = sbyte.MaxValue;
break;
case GLTFComponentType.UnsignedByte:
componentSize = sizeof(byte);
maxValue = byte.MaxValue;
break;
case GLTFComponentType.Short:
componentSize = sizeof(short);
maxValue = short.MaxValue;
break;
case GLTFComponentType.UnsignedShort:
componentSize = sizeof(ushort);
maxValue = ushort.MaxValue;
break;
case GLTFComponentType.UnsignedInt:
componentSize = sizeof(uint);
maxValue = uint.MaxValue;
break;
case GLTFComponentType.Float:
componentSize = sizeof(float);
maxValue = float.MaxValue;
break;
default:
throw new Exception("Unsupported component type.");
}
}
public uint[] AsUIntArray(ref NumericArray contents, byte[] bufferViewData, uint offset)
{
if (contents.AsUInts != null)
{
return contents.AsUInts;
}
if (Type != GLTFAccessorAttributeType.SCALAR)
{
return null;
}
var arr = new uint[Count];
var totalByteOffset = ByteOffset + offset;
uint componentSize;
float maxValue;
GetTypeDetails(ComponentType, out componentSize, out maxValue);
uint stride = BufferView.Value.ByteStride > 0 ? BufferView.Value.ByteStride : componentSize;
for (uint idx = 0; idx < Count; idx++)
{
if (ComponentType == GLTFComponentType.Float)
arr[idx] = (uint)System.Math.Floor(GetFloatElement(bufferViewData, totalByteOffset + idx * stride));
else
arr[idx] = GetUnsignedDiscreteElement(bufferViewData, totalByteOffset + idx * stride, ComponentType);
}
contents.AsUInts = arr;
return arr;
}
public float[] AsFloatArray(ref NumericArray contents, byte[] bufferViewData, uint offset)
{
if (contents.AsUInts != null)
{
return contents.AsFloats;
}
if (Type != GLTFAccessorAttributeType.SCALAR)
{
return null;
}
var arr = new float[Count];
uint totalByteOffset = ByteOffset + offset;
uint componentSize;
float maxValue;
GetTypeDetails(ComponentType, out componentSize, out maxValue);
uint stride = BufferView.Value.ByteStride > 0 ? BufferView.Value.ByteStride : componentSize;
for (uint idx = 0; idx < Count; idx++)
{
if (ComponentType == GLTFComponentType.Float)
arr[idx] = GetFloatElement(bufferViewData, totalByteOffset + idx * stride);
else
arr[idx] = GetUnsignedDiscreteElement(bufferViewData, totalByteOffset + idx * stride, ComponentType);
}
contents.AsFloats = arr;
return arr;
}
public Vector2[] AsVector2Array(ref NumericArray contents, byte[] bufferViewData, uint offset, bool normalizeIntValues = true)
{
if (contents.AsVec2s != null)
{
return contents.AsVec2s;
}
if (Type != GLTFAccessorAttributeType.VEC2)
{
return null;
}
if (ComponentType == GLTFComponentType.UnsignedInt)
{
return null;
}
var arr = new Vector2[Count];
var totalByteOffset = ByteOffset + offset;
uint componentSize;
float maxValue;
GetTypeDetails(ComponentType, out componentSize, out maxValue);
uint stride = BufferView.Value.ByteStride > 0 ? BufferView.Value.ByteStride : componentSize * 2;
if (normalizeIntValues) maxValue = 1;
for (uint idx = 0; idx < Count; idx++)
{
if (ComponentType == GLTFComponentType.Float)
{
arr[idx].X = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 0);
arr[idx].Y = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 1);
}
else
{
arr[idx].X = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 0, ComponentType) / maxValue;
arr[idx].Y = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 1, ComponentType) / maxValue;
}
}
contents.AsVec2s = arr;
return arr;
}
public Vector3[] AsVector3Array(ref NumericArray contents, byte[] bufferViewData, uint offset, bool normalizeIntValues = true)
{
if (contents.AsVec3s != null)
{
return contents.AsVec3s;
}
if (Type != GLTFAccessorAttributeType.VEC3)
{
return null;
}
var arr = new Vector3[Count];
var totalByteOffset = ByteOffset + offset;
uint componentSize;
float maxValue;
GetTypeDetails(ComponentType, out componentSize, out maxValue);
uint stride = BufferView.Value.ByteStride > 0 ? BufferView.Value.ByteStride : componentSize * 3;
if (normalizeIntValues) maxValue = 1;
for (uint idx = 0; idx < Count; idx++)
{
if (ComponentType == GLTFComponentType.Float)
{
arr[idx].X = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 0);
arr[idx].Y = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 1);
arr[idx].Z = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 2);
}
else
{
arr[idx].X = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 0, ComponentType) / maxValue;
arr[idx].Y = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 1, ComponentType) / maxValue;
arr[idx].Z = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 2, ComponentType) / maxValue;
}
}
contents.AsVec3s = arr;
return arr;
}
public Vector4[] AsVector4Array(ref NumericArray contents, byte[] bufferViewData, uint offset, bool normalizeIntValues = true)
{
if (contents.AsVec4s != null)
{
return contents.AsVec4s;
}
if (Type != GLTFAccessorAttributeType.VEC4)
{
return null;
}
if (ComponentType == GLTFComponentType.UnsignedInt)
{
return null;
}
var arr = new Vector4[Count];
var totalByteOffset = ByteOffset + offset;
uint componentSize;
float maxValue;
GetTypeDetails(ComponentType, out componentSize, out maxValue);
uint stride = BufferView.Value.ByteStride > 0 ? BufferView.Value.ByteStride : componentSize * 4;
if (normalizeIntValues) maxValue = 1;
for (uint idx = 0; idx < Count; idx++)
{
if (ComponentType == GLTFComponentType.Float)
{
arr[idx].X = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 0);
arr[idx].Y = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 1);
arr[idx].Z = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 2);
arr[idx].W = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 3);
}
else
{
arr[idx].X = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 0, ComponentType) / maxValue;
arr[idx].Y = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 1, ComponentType) / maxValue;
arr[idx].Z = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 2, ComponentType) / maxValue;
arr[idx].W = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 3, ComponentType) / maxValue;
}
}
contents.AsVec4s = arr;
return arr;
}
public Color[] AsColorArray(ref NumericArray contents, byte[] bufferViewData, uint offset)
{
if (contents.AsColors != null)
{
return contents.AsColors;
}
if (Type != GLTFAccessorAttributeType.VEC3 && Type != GLTFAccessorAttributeType.VEC4)
{
return null;
}
if (ComponentType == GLTFComponentType.UnsignedInt)
{
return null;
}
var arr = new Color[Count];
var totalByteOffset = ByteOffset + offset;
uint componentSize;
float maxValue;
GetTypeDetails(ComponentType, out componentSize, out maxValue);
uint stride = (uint)(BufferView.Value.ByteStride > 0 ? BufferView.Value.ByteStride : componentSize * (Type == GLTFAccessorAttributeType.VEC3 ? 3 : 4));
for (uint idx = 0; idx < Count; idx++)
{
if (ComponentType == GLTFComponentType.Float)
{
arr[idx].R = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 0);
arr[idx].G = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 1);
arr[idx].B = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 2);
if (Type == GLTFAccessorAttributeType.VEC4)
arr[idx].A = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 3);
else
arr[idx].A = 1;
}
else
{
// todo: can be optimized to get these in a block...
arr[idx].R = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 0, ComponentType) / maxValue;
arr[idx].G = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 1, ComponentType) / maxValue;
arr[idx].B = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 2, ComponentType) / maxValue;
if (Type == GLTFAccessorAttributeType.VEC4)
arr[idx].A = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * 3, ComponentType) / maxValue;
else
arr[idx].A = 1;
}
}
contents.AsColors = arr;
return arr;
}
public Vector2[] AsTexcoordArray(ref NumericArray contents, byte[] bufferViewData, uint offset)
{
if (contents.AsTexcoords != null)
{
return contents.AsTexcoords;
}
contents.AsTexcoords = AsVector2Array(ref contents, bufferViewData, offset);
return contents.AsTexcoords;
}
public Vector3[] AsVertexArray(ref NumericArray contents, byte[] bufferViewData, uint offset)
{
if (contents.AsVertices != null)
{
return contents.AsVertices;
}
contents.AsVertices = AsVector3Array(ref contents, bufferViewData, offset);
return contents.AsVertices;
}
public Vector3[] AsNormalArray(ref NumericArray contents, byte[] bufferViewData, uint offset)
{
if (contents.AsNormals != null)
{
return contents.AsNormals;
}
contents.AsNormals = AsVector3Array(ref contents, bufferViewData, offset);
return contents.AsNormals;
}
public Vector4[] AsTangentArray(ref NumericArray contents, byte[] bufferViewData, uint offset)
{
if (contents.AsTangents != null)
{
return contents.AsTangents;
}
contents.AsTangents = AsVector4Array(ref contents, bufferViewData, offset);
return contents.AsTangents;
}
public uint[] AsTriangles(ref NumericArray contents, byte[] bufferViewData, uint offset)
{
if (contents.AsTriangles != null)
{
return contents.AsTriangles;
}
contents.AsTriangles = AsUIntArray(ref contents, bufferViewData, offset);
return contents.AsTriangles;
}
public Matrix4x4[] AsMatrix4x4Array(ref NumericArray contents, byte[] bufferViewData, uint offset, bool normalizeIntValues = true)
{
if (contents.AsMatrix4x4s != null)
{
return contents.AsMatrix4x4s;
}
if (Type != GLTFAccessorAttributeType.MAT4)
{
return null;
}
Matrix4x4[] arr = new Matrix4x4[Count];
uint totalByteOffset = ByteOffset + offset;
uint componentSize;
float maxValue;
GetTypeDetails(ComponentType, out componentSize, out maxValue);
if (normalizeIntValues)
{
maxValue = 1;
}
uint stride = (uint)(BufferView.Value.ByteStride > 0 ? BufferView.Value.ByteStride : componentSize * 16);
for (uint idx = 0; idx < Count; idx++)
{
arr[idx] = new Matrix4x4(Matrix4x4.Identity);
if (ComponentType == GLTFComponentType.Float)
{
for (uint i = 0; i < 16; i++)
{
float value = GetFloatElement(bufferViewData, totalByteOffset + idx * stride + componentSize * i);
arr[idx].SetValue((int)i, value);
}
}
else
{
for (uint i = 0; i < 16; i++)
{
float value = GetDiscreteElement(bufferViewData, totalByteOffset + idx * stride + componentSize * i, ComponentType) / maxValue;
arr[idx].SetValue((int)i, value);
}
}
}
contents.AsMatrix4x4s = arr;
return arr;
}
private static int GetDiscreteElement(byte[] bufferViewData, uint offset, GLTFComponentType type)
{
switch (type)
{
case GLTFComponentType.Byte:
{
return GetByteElement(bufferViewData, offset);
}
case GLTFComponentType.UnsignedByte:
{
return GetUByteElement(bufferViewData, offset);
}
case GLTFComponentType.Short:
{
return GetShortElement(bufferViewData, offset);
}
case GLTFComponentType.UnsignedShort:
{
return GetUShortElement(bufferViewData, offset);
}
default:
{
throw new Exception("Unsupported type passed in: " + type);
}
}
}
// technically byte and short are not spec compliant for unsigned types, but various files have it
private static uint GetUnsignedDiscreteElement(byte[] bufferViewData, uint offset, GLTFComponentType type)
{
switch (type)
{
case GLTFComponentType.Byte:
{
return (uint)GetByteElement(bufferViewData, offset);
}
case GLTFComponentType.UnsignedByte:
{
return GetUByteElement(bufferViewData, offset);
}
case GLTFComponentType.Short:
{
return (uint)GetShortElement(bufferViewData, offset);
}
case GLTFComponentType.UnsignedShort:
{
return GetUShortElement(bufferViewData, offset);
}
case GLTFComponentType.UnsignedInt:
{
return GetUIntElement(bufferViewData, offset);
}
default:
{
throw new Exception("Unsupported type passed in: " + type);
}
}
}
}
public enum GLTFComponentType
{
Byte = 5120,
UnsignedByte = 5121,
Short = 5122,
UnsignedShort = 5123,
UnsignedInt = 5125,
Float = 5126
}
public enum GLTFAccessorAttributeType
{
SCALAR,
VEC2,
VEC3,
VEC4,
MAT2,
MAT3,
MAT4
}
/// <summary>
[StructLayout(LayoutKind.Explicit)]
public struct NumericArray
{
[FieldOffset(0)]
public uint[] AsUInts;
[FieldOffset(0)]
public float[] AsFloats;
[FieldOffset(0)]
public Vector2[] AsVec2s;
[FieldOffset(0)]
public Vector3[] AsVec3s;
[FieldOffset(0)]
public Vector4[] AsVec4s;
[FieldOffset(0)]
public Matrix4x4[] AsMatrix4x4s;
[FieldOffset(0)]
public Color[] AsColors;
[FieldOffset(0)]
public Vector2[] AsTexcoords;
[FieldOffset(0)]
public Vector3[] AsVertices;
[FieldOffset(0)]
public Vector3[] AsNormals;
[FieldOffset(0)]
public Vector4[] AsTangents;
[FieldOffset(0)]
public uint[] AsTriangles;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9fdb27ce25eaa9e418627129cb42bd53
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,91 @@
using System;
using Newtonsoft.Json;
namespace GLTF.Schema
{
public class AccessorSparse : GLTFProperty
{
/// <summary>
/// Number of entries stored in the sparse array.
/// <minimum>1</minimum>
/// </summary>
public int Count;
/// <summary>
/// Index array of size `count` that points to those accessor attributes that
/// deviate from their initialization value. Indices must strictly increase.
/// </summary>
public AccessorSparseIndices Indices;
/// <summary>
/// "Array of size `count` times number of components, storing the displaced
/// accessor attributes pointed by `indices`. Substituted values must have
/// the same `componentType` and number of components as the base accessor.
/// </summary>
public AccessorSparseValues Values;
public AccessorSparse()
{
}
public AccessorSparse(AccessorSparse accessorSparse, GLTFRoot gltfRoot) : base(accessorSparse)
{
if (accessorSparse == null) return;
Count = accessorSparse.Count;
Indices = new AccessorSparseIndices(accessorSparse.Indices, gltfRoot);
Values = new AccessorSparseValues(accessorSparse.Values, gltfRoot);
}
public static AccessorSparse Deserialize(GLTFRoot root, JsonReader reader)
{
var accessorSparse = new AccessorSparse();
if (reader.Read() && reader.TokenType != JsonToken.StartObject)
{
throw new Exception("Asset must be an object.");
}
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
{
var curProp = reader.Value.ToString();
switch (curProp)
{
case "count":
accessorSparse.Count = reader.ReadAsInt32().Value;
break;
case "indices":
accessorSparse.Indices = AccessorSparseIndices.Deserialize(root, reader);
break;
case "values":
accessorSparse.Values = AccessorSparseValues.Deserialize(root, reader);
break;
default:
accessorSparse.DefaultPropertyDeserializer(root, reader);
break;
}
}
return accessorSparse;
}
public override void Serialize(JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("count");
writer.WriteValue(Count);
writer.WritePropertyName("indices");
Indices.Serialize(writer);
writer.WritePropertyName("values");
Values.Serialize(writer);
base.Serialize(writer);
writer.WriteEndObject();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 30350fa0a44956c4084506e37779d503
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,95 @@
using System;
using Newtonsoft.Json;
namespace GLTF.Schema
{
public class AccessorSparseIndices : GLTFProperty
{
/// <summary>
/// The index of the bufferView with sparse indices.
/// Referenced bufferView can't have ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER target.
/// </summary>
public BufferViewId BufferView;
/// <summary>
/// The offset relative to the start of the bufferView in bytes. Must be aligned.
/// <minimum>0</minimum>
/// </summary>
public int ByteOffset;
/// <summary>
/// The indices data type. Valid values correspond to WebGL enums:
/// `5121` (UNSIGNED_BYTE)
/// `5123` (UNSIGNED_SHORT)
/// `5125` (UNSIGNED_INT)
/// </summary>
public GLTFComponentType ComponentType;
public AccessorSparseIndices()
{
}
public AccessorSparseIndices(AccessorSparseIndices accessorSparseIndices, GLTFRoot gltfRoot) : base(accessorSparseIndices)
{
if (accessorSparseIndices == null) return;
BufferView = new BufferViewId(accessorSparseIndices.BufferView, gltfRoot);
ByteOffset = accessorSparseIndices.ByteOffset;
ComponentType = accessorSparseIndices.ComponentType;
}
public static AccessorSparseIndices Deserialize(GLTFRoot root, JsonReader reader)
{
var indices = new AccessorSparseIndices();
if (reader.Read() && reader.TokenType != JsonToken.StartObject)
{
throw new Exception("Asset must be an object.");
}
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
{
var curProp = reader.Value.ToString();
switch (curProp)
{
case "bufferView":
indices.BufferView = BufferViewId.Deserialize(root, reader);
break;
case "byteOffset":
indices.ByteOffset = reader.ReadAsInt32().Value;
break;
case "componentType":
indices.ComponentType = (GLTFComponentType) reader.ReadAsInt32().Value;
break;
default:
indices.DefaultPropertyDeserializer(root, reader);
break;
}
}
return indices;
}
public override void Serialize(JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("bufferView");
writer.WriteValue(BufferView.Id);
if (ByteOffset != 0)
{
writer.WritePropertyName("byteOffset");
writer.WriteValue(ByteOffset);
}
writer.WritePropertyName("componentType");
writer.WriteValue((int)ComponentType);
base.Serialize(writer);
writer.WriteEndObject();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0606e7ff683a71a4098fadddab4663f8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,80 @@
using System;
using Newtonsoft.Json;
namespace GLTF.Schema
{
public class AccessorSparseValues : GLTFProperty
{
/// <summary>
/// The index of the bufferView with sparse values.
/// Referenced bufferView can't have ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER target.
/// </summary>
public BufferViewId BufferView;
/// <summary>
/// The offset relative to the start of the bufferView in bytes. Must be aligned.
/// <minimum>0</minimum>
/// </summary>
public int ByteOffset = 0;
public AccessorSparseValues()
{
}
public AccessorSparseValues(AccessorSparseValues accessorSparseValues, GLTFRoot gltfRoot) : base(accessorSparseValues)
{
if (accessorSparseValues == null) return;
BufferView = new BufferViewId(accessorSparseValues.BufferView, gltfRoot);
ByteOffset = accessorSparseValues.ByteOffset;
}
public static AccessorSparseValues Deserialize(GLTFRoot root, JsonReader reader)
{
var values = new AccessorSparseValues();
if (reader.Read() && reader.TokenType != JsonToken.StartObject)
{
throw new Exception("Asset must be an object.");
}
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
{
var curProp = reader.Value.ToString();
switch (curProp)
{
case "bufferView":
values.BufferView = BufferViewId.Deserialize(root, reader);
break;
case "byteOffset":
values.ByteOffset = reader.ReadAsInt32().Value;
break;
default:
values.DefaultPropertyDeserializer(root, reader);
break;
}
}
return values;
}
public override void Serialize(JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("bufferView");
writer.WriteValue(BufferView.Id);
if (ByteOffset != 0)
{
writer.WritePropertyName("byteOffset");
writer.WriteValue(ByteOffset);
}
base.Serialize(writer);
writer.WriteEndObject();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d00bc2c09c68ec8408bd7b0069b855d0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,73 @@
using Newtonsoft.Json;
namespace GLTF.Schema
{
/// <summary>
/// Targets an animation's sampler at a node's property.
/// </summary>
public class AnimationChannel : GLTFProperty
{
/// <summary>
/// The index of a sampler in this animation used to compute the value for the
/// target, e.g., a node's translation, rotation, or scale (TRS).
/// </summary>
public AnimationSamplerId Sampler;
/// <summary>
/// The index of the node and TRS property to target.
/// </summary>
public AnimationChannelTarget Target;
public AnimationChannel()
{
}
public AnimationChannel(AnimationChannel animationChannel, GLTFRoot root) : base(animationChannel)
{
if (animationChannel == null) return;
Sampler = new AnimationSamplerId(animationChannel.Sampler, root);
Target = new AnimationChannelTarget(animationChannel.Target, root);
}
public static AnimationChannel Deserialize(GLTFRoot root, JsonReader reader, GLTFAnimation anim)
{
var animationChannel = new AnimationChannel();
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
{
var curProp = reader.Value.ToString();
switch (curProp)
{
case "sampler":
animationChannel.Sampler = AnimationSamplerId.Deserialize(root, anim, reader);
break;
case "target":
animationChannel.Target = AnimationChannelTarget.Deserialize(root, reader);
break;
default:
animationChannel.DefaultPropertyDeserializer(root, reader);
break;
}
}
return animationChannel;
}
public override void Serialize(JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("sampler");
writer.WriteValue(Sampler.Id);
writer.WritePropertyName("target");
Target.Serialize(writer);
base.Serialize(writer);
writer.WriteEndObject();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5e7ba1c2598f9aa48a88e0e2730433b6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,94 @@
using System;
using GLTF.Extensions;
using Newtonsoft.Json;
namespace GLTF.Schema
{
/// <summary>
/// The index of the node and TRS property that an animation channel targets.
/// </summary>
public class AnimationChannelTarget : GLTFProperty
{
/// <summary>
/// The index of the node to target.
/// </summary>
public NodeId Node;
/// <summary>
/// The name of the node's TRS property to modify.
/// </summary>
public string Path;
public static AnimationChannelTarget Deserialize(GLTFRoot root, JsonReader reader)
{
var animationChannelTarget = new AnimationChannelTarget();
if (reader.Read() && reader.TokenType != JsonToken.StartObject)
{
throw new Exception("Animation channel target must be an object.");
}
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
{
var curProp = reader.Value.ToString();
switch (curProp)
{
case "node":
animationChannelTarget.Node = NodeId.Deserialize(root, reader);
break;
case "path":
animationChannelTarget.Path = reader.ReadAsString();// reader.ReadStringEnum<GLTFAnimationChannelPath>();
break;
// TODO: add KHR_animation_pointer import
// case "pointer":
// break;
default:
animationChannelTarget.DefaultPropertyDeserializer(root, reader);
break;
}
}
return animationChannelTarget;
}
public AnimationChannelTarget()
{
}
public AnimationChannelTarget(AnimationChannelTarget channelTarget, GLTFRoot gltfRoot) : base(channelTarget)
{
if (channelTarget == null) return;
Node = channelTarget.Node != null ? new NodeId(channelTarget.Node, gltfRoot) : null;
Path = channelTarget.Path;
}
public override void Serialize(JsonWriter writer)
{
writer.WriteStartObject();
// in KHR_animation2 node might not exist, instead it has an extensions field
if (Node != null)
{
writer.WritePropertyName("node");
writer.WriteValue(Node.Id);
}
writer.WritePropertyName("path");
writer.WriteValue(Path.ToString());
base.Serialize(writer);
writer.WriteEndObject();
}
}
public enum GLTFAnimationChannelPath
{
translation,
rotation,
scale,
weights
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8111941d8c535694480020d2938d7ead
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,103 @@
using GLTF.Extensions;
using Newtonsoft.Json;
namespace GLTF.Schema
{
public enum InterpolationType
{
LINEAR,
STEP,
CATMULLROMSPLINE,
CUBICSPLINE
}
/// <summary>
/// Combines input and output accessors with an interpolation algorithm to define a keyframe graph (but not its target).
/// </summary>
public class AnimationSampler : GLTFProperty
{
/// <summary>
/// The index of an accessor containing keyframe input values, e.G., time.
/// That accessor must have componentType `FLOAT`. The values represent time in
/// seconds with `time[0] >= 0.0`, and strictly increasing values,
/// i.e., `time[n + 1] > time[n]`
/// </summary>
public AccessorId Input;
/// <summary>
/// Interpolation algorithm. When an animation targets a node's rotation,
/// and the animation's interpolation is `\"LINEAR\"`, spherical linear
/// interpolation (slerp) should be used to interpolate quaternions. When
/// interpolation is `\"STEP\"`, animated value remains constant to the value
/// of the first point of the timeframe, until the next timeframe.
/// </summary>
public InterpolationType Interpolation;
/// <summary>
/// The index of an accessor, containing keyframe output values. Output and input
/// accessors must have the same `count`. When sampler is used with TRS target,
/// output accessor's componentType must be `FLOAT`.
/// </summary>
public AccessorId Output;
public AnimationSampler()
{
}
public AnimationSampler(AnimationSampler animationSampler, GLTFRoot gltfRoot) : base(animationSampler)
{
if (animationSampler == null) return;
Input = new AccessorId(animationSampler.Input, gltfRoot);
Interpolation = animationSampler.Interpolation;
Output = new AccessorId(animationSampler.Output, gltfRoot);
}
public static AnimationSampler Deserialize(GLTFRoot root, JsonReader reader)
{
var animationSampler = new AnimationSampler();
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
{
var curProp = reader.Value.ToString();
switch (curProp)
{
case "input":
animationSampler.Input = AccessorId.Deserialize(root, reader);
break;
case "interpolation":
animationSampler.Interpolation = reader.ReadStringEnum<InterpolationType>();
break;
case "output":
animationSampler.Output = AccessorId.Deserialize(root, reader);
break;
default:
animationSampler.DefaultPropertyDeserializer(root, reader);
break;
}
}
return animationSampler;
}
public override void Serialize(JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("input");
writer.WriteValue(Input.Id);
// the spec defines "LINEAR" as default, but we need to explicitly export this since there are issues with Google SceneViewer when no interpolation is specified
writer.WritePropertyName("interpolation");
writer.WriteValue(Interpolation.ToString());
writer.WritePropertyName("output");
writer.WriteValue(Output.Id);
base.Serialize(writer);
writer.WriteEndObject();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2fda6c6e1290a7b44bfefed8f5d16c5a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,105 @@
using System;
using Newtonsoft.Json;
namespace GLTF.Schema
{
/// <summary>
/// Metadata about the glTF asset.
/// </summary>
public class Asset : GLTFProperty
{
/// <summary>
/// A copyright message suitable for display to credit the content creator.
/// </summary>
public string Copyright;
/// <summary>
/// Tool that generated this glTF model. Useful for debugging.
/// </summary>
public string Generator;
/// <summary>
/// The glTF version.
/// </summary>
public string Version;
/// <summary>
/// The minimum glTF version that this asset targets.
/// </summary>
public string MinVersion;
public Asset()
{
}
public Asset(Asset asset) : base(asset)
{
if (asset == null) return;
Copyright = asset.Copyright;
Generator = asset.Generator;
Version = asset.Version;
MinVersion = asset.MinVersion;
}
public static Asset Deserialize(GLTFRoot root, JsonReader reader)
{
var asset = new Asset();
if (reader.Read() && reader.TokenType != JsonToken.StartObject)
{
throw new Exception("Asset must be an object.");
}
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
{
var curProp = reader.Value.ToString();
switch (curProp)
{
case "copyright":
asset.Copyright = reader.ReadAsString();
break;
case "generator":
asset.Generator = reader.ReadAsString();
break;
case "version":
asset.Version = reader.ReadAsString();
break;
case "minVersion":
asset.MinVersion = reader.ReadAsString();
break;
default:
asset.DefaultPropertyDeserializer(root, reader);
break;
}
}
return asset;
}
public override void Serialize(JsonWriter writer)
{
writer.WriteStartObject();
if (Copyright != null)
{
writer.WritePropertyName("copyright");
writer.WriteValue(Copyright);
}
if (Generator != null)
{
writer.WritePropertyName("generator");
writer.WriteValue(Generator);
}
writer.WritePropertyName("version");
writer.WriteValue(Version);
base.Serialize(writer);
writer.WriteEndObject();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 85a3a816df09cc345ab4002fe5a7cf11
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,139 @@
using GLTF.Utilities;
using Newtonsoft.Json;
namespace GLTF.Schema
{
public enum BufferViewTarget
{
/// <summary>
/// For animation or
/// </summary>
None = 0,
/// <summary>
/// For vertex data
/// </summary>
ArrayBuffer = 34962,
/// <summary>
/// For index data
/// </summary>
ElementArrayBuffer = 34963,
}
/// <summary>
/// A view into a buffer generally representing a subset of the buffer.
/// </summary>
public class BufferView : GLTFChildOfRootProperty
{
/// <summary>
/// The index of the buffer.
/// </summary>
public BufferId Buffer;
/// <summary>
/// The offset into the buffer in bytes.
/// <minimum>0</minimum>
/// </summary>
public uint ByteOffset;
/// <summary>
/// The length of the bufferView in bytes.
/// <minimum>0</minimum>
/// </summary>
public uint ByteLength;
/// <summary>
/// The stride, in bytes, between vertex attributes or other interleavable data.
/// When this is zero, data is tightly packed.
/// <minimum>0</minimum>
/// <maximum>255</maximum>
/// </summary>
public uint ByteStride;
/// <summary>
/// The target that the WebGL buffer should be bound to.
/// All valid values correspond to WebGL enums.
/// When this is not provided, the bufferView contains animation or skin data.
/// </summary>
public BufferViewTarget Target = BufferViewTarget.None;
public BufferView()
{
}
public BufferView(BufferView bufferView, GLTFRoot gltfRoot) : base(bufferView, gltfRoot)
{
Buffer = new BufferId(bufferView.Buffer, gltfRoot);
ByteOffset = bufferView.ByteOffset;
ByteLength = bufferView.ByteLength;
ByteStride = bufferView.ByteStride;
Target = bufferView.Target;
}
public static BufferView Deserialize(GLTFRoot root, JsonReader reader)
{
var bufferView = new BufferView();
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
{
var curProp = reader.Value.ToString();
switch (curProp)
{
case "buffer":
bufferView.Buffer = BufferId.Deserialize(root, reader);
break;
case "byteOffset":
bufferView.ByteOffset = reader.ReadDoubleAsUInt32();
break;
case "byteLength":
bufferView.ByteLength = reader.ReadDoubleAsUInt32();
break;
case "byteStride":
bufferView.ByteStride = reader.ReadDoubleAsUInt32();
break;
case "target":
bufferView.Target = (BufferViewTarget)reader.ReadAsInt32().Value;
break;
default:
bufferView.DefaultPropertyDeserializer(root, reader);
break;
}
}
return bufferView;
}
public override void Serialize(JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("buffer");
writer.WriteValue(Buffer.Id);
if (ByteOffset != 0)
{
writer.WritePropertyName("byteOffset");
writer.WriteValue(ByteOffset);
}
writer.WritePropertyName("byteLength");
writer.WriteValue(ByteLength);
if (ByteStride != 0)
{
writer.WritePropertyName("byteStride");
writer.WriteValue(ByteStride);
}
if (Target != BufferViewTarget.None)
{
writer.WritePropertyName("target");
writer.WriteValue((int)Target);
}
base.Serialize(writer);
writer.WriteEndObject();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d729c33bb2a00cc4d9b1dfb86a5328e0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,101 @@
using System;
using Newtonsoft.Json;
namespace GLTF.Schema
{
/// <summary>
/// An orthographic camera containing properties to create an orthographic
/// projection matrix.
/// </summary>
public class CameraOrthographic : GLTFProperty
{
/// <summary>
/// The floating-point horizontal magnification of the view.
/// </summary>
public double XMag;
/// <summary>
/// The floating-point vertical magnification of the view.
/// </summary>
public double YMag;
/// <summary>
/// The floating-point distance to the far clipping plane.
/// </summary>
public double ZFar;
/// <summary>
/// The floating-point distance to the near clipping plane.
/// </summary>
public double ZNear;
public CameraOrthographic()
{
}
public CameraOrthographic(CameraOrthographic cameraOrthographic) : base(cameraOrthographic)
{
XMag = cameraOrthographic.XMag;
YMag = cameraOrthographic.YMag;
ZFar = cameraOrthographic.ZFar;
ZNear = cameraOrthographic.ZNear;
}
public static CameraOrthographic Deserialize(GLTFRoot root, JsonReader reader)
{
var cameraOrthographic = new CameraOrthographic();
if (reader.Read() && reader.TokenType != JsonToken.StartObject)
{
throw new Exception("Orthographic camera must be an object.");
}
while (reader.Read() && reader.TokenType == JsonToken.PropertyName)
{
var curProp = reader.Value.ToString();
switch (curProp)
{
case "xmag":
cameraOrthographic.XMag = reader.ReadAsDouble().Value;
break;
case "ymag":
cameraOrthographic.YMag = reader.ReadAsDouble().Value;
break;
case "zfar":
cameraOrthographic.ZFar = reader.ReadAsDouble().Value;
break;
case "znear":
cameraOrthographic.ZNear = reader.ReadAsDouble().Value;
break;
default:
cameraOrthographic.DefaultPropertyDeserializer(root, reader);
break;
}
}
return cameraOrthographic;
}
public override void Serialize(JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("xmag");
writer.WriteValue(XMag);
writer.WritePropertyName("ymag");
writer.WriteValue(YMag);
writer.WritePropertyName("zfar");
writer.WriteValue(ZFar);
writer.WritePropertyName("znear");
writer.WriteValue(ZNear);
base.Serialize(writer);
writer.WriteEndObject();
}
}
}

Some files were not shown because too many files have changed in this diff Show More