using System;
using System.Runtime.InteropServices;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SlatedGameToolkit.Framework.Exceptions;
using SlatedGameToolkit.Framework.Graphics.OpenGL;
using SlatedGameToolkit.Framework.Graphics.Textures;
namespace SlatedGameToolkit.Commons.Loaders
{
public static class TextureLoader
{
///
/// Loads a texture using SDL2's image library.
/// Therefore, technically, this function should be able to laod any format SDL2 Image can load.
///
/// The path of the texture to load.
/// The OpenGL context the texture is to be associated with. May be null.
/// An OpenGL Texture associated with the given context.
public static Texture LoadTexture(string path, GLContext glContext)
{
TextureData textureData;
using (Image image = Image.Load(path))
{
byte[] pixelData;
Span pixelDataSpan;
if (image.TryGetSinglePixelSpan(out pixelDataSpan)) {
pixelData = MemoryMarshal.AsBytes(pixelDataSpan).ToArray();
} else {
throw new FrameworkUsageException("Image too large!");
}
textureData = new TextureData(image.Width, image.Height, pixelData);
}
return new Texture(textureData, glContext);
}
}
}