107 lines
3.4 KiB
C#
107 lines
3.4 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Text.Json;
|
|
using ReFuel.Gltf.IO;
|
|
|
|
namespace ReFuel.Gltf
|
|
{
|
|
public class GltfImage : GltfIdObject
|
|
{
|
|
private GltfSmartId<GltfBufferView> _bufferView;
|
|
public override GltfObjectKind Kind => GltfObjectKind.Image;
|
|
|
|
public string? Name { get; set; }
|
|
public Uri? Uri { get; set; }
|
|
public string? MediaType { get; set; }
|
|
|
|
public GltfBufferView? BufferView
|
|
{
|
|
get => _bufferView.IsSet ? _bufferView.Value : null;
|
|
set
|
|
{
|
|
if (value is null)
|
|
{
|
|
_bufferView.Reset();
|
|
}
|
|
else
|
|
{
|
|
_bufferView.Value = value;
|
|
}
|
|
}
|
|
}
|
|
|
|
internal GltfImage(GltfDocument document) : base(document)
|
|
{
|
|
_bufferView = new GltfSmartId<GltfBufferView>(document.BufferViews);
|
|
}
|
|
|
|
public Stream Open(string? pwd = null, IGltfStreamProvider? provider = null)
|
|
{
|
|
if (Uri == null)
|
|
{
|
|
throw new Exception("Only images with a URI property are to be opened.");
|
|
}
|
|
|
|
if (Uri.IsAbsoluteUri)
|
|
{
|
|
switch (Uri.Scheme)
|
|
{
|
|
case "file":
|
|
if (provider != null)
|
|
{
|
|
return provider.OpenFile(pwd, Uri) ?? throw new FileNotFoundException(Uri.ToString());
|
|
}
|
|
else
|
|
{
|
|
string path = Path.Combine(pwd ?? string.Empty, Uri.LocalPath);
|
|
return File.OpenRead(path);
|
|
}
|
|
case "data":
|
|
return DataUriStream.FromUri(Uri.OriginalString);
|
|
}
|
|
}
|
|
|
|
// otherwise
|
|
|
|
if (provider != null)
|
|
return provider.OpenFile(pwd, Uri) ?? throw new FileNotFoundException(Uri.ToString());
|
|
else
|
|
return File.OpenRead(Path.Combine(pwd ?? string.Empty, Uri.LocalPath));
|
|
|
|
// throw new Exception("Unrecognized URI scheme.");
|
|
}
|
|
|
|
internal override void Deserialize(JsonElement element)
|
|
{
|
|
if (element.ValueKind != JsonValueKind.Object)
|
|
throw new Exception("Expected a JSON object for glTF image node.");
|
|
|
|
foreach (JsonProperty property in element.EnumerateObject())
|
|
{
|
|
switch (property.Name)
|
|
{
|
|
case "uri":
|
|
Uri = new Uri(property.Value.GetString() ?? throw new Exception("Expected a string."), UriKind.RelativeOrAbsolute);
|
|
break;
|
|
case "mimeType":
|
|
MediaType = property.Value.GetString() ?? throw new Exception("Expected a string.");
|
|
break;
|
|
case "bufferView":
|
|
_bufferView.Id = property.Value.GetInt32();
|
|
break;
|
|
case "name":
|
|
Name = property.Value.GetString();
|
|
break;
|
|
}
|
|
}
|
|
|
|
DeserializeCommon(element);
|
|
}
|
|
|
|
internal override void Serialize(Utf8JsonWriter writer)
|
|
{
|
|
throw new NotImplementedException();
|
|
}
|
|
}
|
|
}
|