SOURCE DUMP v1

This commit is contained in:
Rian Drake 2026-10-15 14:09:11 +13:00
commit fb20299e9d
9 changed files with 768360 additions and 0 deletions

View file

@ -0,0 +1,30 @@
using Brutal.TextureApi;
namespace Brutal.TextureApi.Stb;
public static class StbDataTypeExtensions
{
public static StbApi.Stb.DataType ToStbDataType(this TextureFormat format)
{
switch (format)
{
case TextureFormat.R8_UNorm:
case TextureFormat.R8G8_UNorm:
case TextureFormat.R8G8B8_UNorm:
case TextureFormat.R8G8B8A8_UNorm:
return StbApi.Stb.DataType._8Bit;
case TextureFormat.R16_UNorm:
case TextureFormat.R16G16_UNorm:
case TextureFormat.R16G16B16_UNorm:
case TextureFormat.R16G16B16A16_UNorm:
return StbApi.Stb.DataType._16Bit;
case TextureFormat.R32_SFloat:
case TextureFormat.R32G32_SFloat:
case TextureFormat.R32G32B32_SFloat:
case TextureFormat.R32G32B32A32_SFloat:
return StbApi.Stb.DataType.Float;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, "TextureFormat not supported by Stb");
}
}
}

View file

@ -0,0 +1,73 @@
using System.Diagnostics;
using Brutal.Numerics;
using Brutal.Pointers.Extensions;
namespace Brutal.TextureApi.Stb;
public abstract partial class StbTexture : ITexture
{
internal struct CreateInfo
{
internal required int2 Extent;
internal required int Channels;
internal required int BytesPerChannel;
}
#region ITexture
public unsafe Span<byte> Data => new(GetDataPointer(), ElementCount.Of(_dataSize));
public TexelCount3 Extent => new(NativeInfo.Extent.X, NativeInfo.Extent.Y, 1);
public abstract TextureFormat Format { get; }
public int LayerCount => 1;
public int LevelCount => 1;
public int FaceCount => 1;
public bool IsCubemap => false;
public bool IsArray => false;
public int DimensionCount => 2;
public ByteSize RowPitch(int level)
{
if (level < 0 || level >= LevelCount)
throw new ArgumentOutOfRangeException(nameof(level), level, $"Level must be in range [0, {LevelCount})");
return _rowPitch;
}
/// <summary>
/// Returns the bytes that the image takes up.
/// </summary>
/// <param name="level">Must be 0</param>
/// <param name="layer">Must be 0</param>
/// <param name="face">Must be 0</param>
/// <returns></returns>
public unsafe Span<byte> ImageData(int level, int layer, int face)
{
if (level != 0 || layer != 0 || face != 0)
throw new TextureException($"level, layer and face must all be 0 for STB textures");
return new Span<byte>(Data.AsPointer(), Data.Length);
}
#endregion
public int Channels => NativeInfo.Channels;
public void Destroy()
{
FreeNativeResources();
}
internal readonly CreateInfo NativeInfo;
protected abstract unsafe byte* GetDataPointer();
private readonly ByteSize _dataSize;
private readonly ByteSize _rowPitch;
internal StbTexture(CreateInfo info)
{
Debug.Assert(FaceCount == 1 && LevelCount == 1 && LayerCount == 1);
NativeInfo = info;
_dataSize = ByteSize.Of(
NativeInfo.Extent.X * NativeInfo.Extent.Y * NativeInfo.Channels * NativeInfo.BytesPerChannel
);
_rowPitch = ByteSize.Of(NativeInfo.Extent.X * NativeInfo.Channels * NativeInfo.BytesPerChannel);
}
protected abstract void FreeNativeResources();
}

View file

@ -0,0 +1,52 @@
using Brutal.Numerics;
using Brutal.StbApi;
using Brutal.TextureApi;
namespace Brutal.TextureApi.Stb;
public class StbTexture16 : StbTexture
{
internal StbTexture16(StbImage16 image)
: base(
new CreateInfo
{
Extent = new int2(image.Width, image.Height),
Channels = image.Channels,
BytesPerChannel = 2,
}
)
{
_image = image;
}
public override TextureFormat Format
{
get
{
return _image.Channels switch
{
1 => TextureFormat.R16_UNorm,
2 => TextureFormat.R16G16_UNorm,
3 => TextureFormat.R16G16B16_UNorm,
4 => TextureFormat.R16G16B16A16_UNorm,
_ => throw new ArgumentOutOfRangeException(),
};
}
}
protected override unsafe byte* GetDataPointer()
{
return (byte*)_image.Data;
}
protected override void FreeNativeResources()
{
if (_image.IsNotNull())
{
_image.Dispose();
_image = default;
}
}
private StbImage16 _image;
}

View file

@ -0,0 +1,52 @@
using Brutal.Numerics;
using Brutal.StbApi;
using Brutal.TextureApi;
namespace Brutal.TextureApi.Stb;
public class StbTexture8 : StbTexture
{
internal StbTexture8(StbImage8 image)
: base(
new CreateInfo
{
Extent = new int2(image.Width, image.Height),
Channels = image.Channels,
BytesPerChannel = 1,
}
)
{
_image = image;
}
public override TextureFormat Format
{
get
{
return _image.Channels switch
{
1 => TextureFormat.R8_UNorm,
2 => TextureFormat.R8G8_UNorm,
3 => TextureFormat.R8G8B8_UNorm,
4 => TextureFormat.R8G8B8A8_UNorm,
_ => throw new ArgumentOutOfRangeException(),
};
}
}
protected override unsafe byte* GetDataPointer()
{
return _image.Data;
}
protected override void FreeNativeResources()
{
if (_image.IsNotNull())
{
_image.Dispose();
_image = default;
}
}
private StbImage8 _image;
}

View file

@ -0,0 +1,7 @@
namespace Brutal.TextureApi.Stb;
public class StbTextureException : TextureException
{
public StbTextureException(string message)
: base(message) { }
}

View file

@ -0,0 +1,52 @@
using Brutal.Numerics;
using Brutal.StbApi;
using Brutal.TextureApi;
namespace Brutal.TextureApi.Stb;
public class StbTextureF : StbTexture
{
internal StbTextureF(StbImageF image)
: base(
new CreateInfo
{
Extent = new int2(image.Width, image.Height),
Channels = image.Channels,
BytesPerChannel = 4,
}
)
{
_image = image;
}
public override TextureFormat Format
{
get
{
return _image.Channels switch
{
1 => TextureFormat.R32_SFloat,
2 => TextureFormat.R32G32_SFloat,
3 => TextureFormat.R32G32B32_SFloat,
4 => TextureFormat.R32G32B32A32_SFloat,
_ => throw new ArgumentOutOfRangeException(),
};
}
}
protected override unsafe byte* GetDataPointer()
{
return (byte*)_image.Data;
}
protected override void FreeNativeResources()
{
if (_image.IsNotNull())
{
_image.Dispose();
_image = default;
}
}
private StbImageF _image;
}

View file

@ -0,0 +1,178 @@
using System.Collections.Frozen;
using Brutal.Pointers.Extensions;
namespace Brutal.TextureApi.Stb;
public static partial class Loader
{
public static StbTexture LoadFromFile(string filePath, LoadSettings? loadInfo = null)
{
// Load settings can try force data type, otherwise use file's native data type
var dataType = GetForceDataType(loadInfo) ?? GetNativeDataType(filePath);
// Load settings can try force channel count, otherwise use file's native channel count
var channelCount = GetForceChannels(loadInfo) ?? 0;
switch (dataType)
{
case StbApi.Stb.DataType._8Bit:
{
var handle = StbApi.Stb.Load(filePath, channelCount);
if (handle.IsNotNull())
{
return new StbTexture8(handle);
}
break;
}
case StbApi.Stb.DataType._16Bit:
{
var handle = StbApi.Stb.Load16(filePath, channelCount);
if (handle.IsNotNull())
{
return new StbTexture16(handle);
}
break;
}
case StbApi.Stb.DataType.Float:
{
var handle = StbApi.Stb.LoadF(filePath, channelCount);
if (handle.IsNotNull())
{
return new StbTextureF(handle);
}
break;
}
}
throw new StbTextureReadException(
$"Failed to load texture from filePath \"{filePath}\", failure reason: {(StbApi.Stb.TryGetFailureReason(out var reason) ? reason : "Unknown")}"
);
}
public static unsafe StbTexture LoadFromMemory(ReadOnlySpan<byte> data, LoadSettings? loadInfo = null)
{
// Load settings can try force data type, otherwise use file's native data type
var dataType = GetForceDataType(loadInfo) ?? GetNativeDataType(data);
// Load settings can try force channel count, otherwise use file's native channel count
var channelCount = GetForceChannels(loadInfo) ?? 0;
switch (dataType)
{
case StbApi.Stb.DataType._8Bit:
{
var handle = StbApi.Stb.LoadFromMemory(data, channelCount);
if (handle.IsNotNull())
{
return new StbTexture8(handle);
}
break;
}
case StbApi.Stb.DataType._16Bit:
{
var handle = StbApi.Stb.Load16FromMemory(data, channelCount);
if (handle.IsNotNull())
{
return new StbTexture16(handle);
}
break;
}
case StbApi.Stb.DataType.Float:
{
var handle = StbApi.Stb.LoadFFromMemory(data, channelCount);
if (handle.IsNotNull())
{
return new StbTextureF(handle);
}
break;
}
}
throw new StbTextureReadException(
$"Failed to load texture from data at 0x{(nint)data.AsPointer()}, failure reason: {(StbApi.Stb.TryGetFailureReason(out var reason) ? reason : "Unknown")}"
);
}
public class LoadSettings : TextureLoadSettings
{
/// <summary>
/// Force StbTextureFactory to load image data into a texture of the target data type
/// </summary>
/// <remarks>
/// If set, the factory will perform conversion into the target type, using scaling between 8-16 bit
/// and/or HDR&lt;=&gt;LDR conversion as required.
/// <para/>
/// For example, loading a .hdr file as DataType._16bit will firstly load
/// float data from the source, then use LDR to HDR conversion into 8 bit, then upscale to 16 bit.
/// <para/>
/// If not set, StbTextureFactory load functions will default to loading textures using their 'native' data type.
/// </remarks>
public StbApi.Stb.DataType? ForceDataType;
/// <summary>
/// Force StbTextureFactory to load image data into a texture with the target channel count.
/// </summary>
/// <remarks>
/// If set, the factory will add or remove channels when loading the data.
/// <para/>
/// Any added color channels (1-3) will be zeroed, alpha channels (4) will be set to max value.
/// </remarks>
public int? ForceChannels;
/// <summary>
/// A LoadSettings preset which will force StbTextureFactory to load textures into R8G8B8A8_UNorm format
/// </summary>
public static readonly LoadSettings ForceRgba8 = new()
{
ForceChannels = 4,
ForceDataType = StbApi.Stb.DataType._8Bit,
};
}
#region Private
private static StbApi.Stb.DataType? GetForceDataType(LoadSettings? loadInfo)
{
var settings = loadInfo ?? new();
return settings.ForceDataType;
}
private static int? GetForceChannels(LoadSettings? loadInfo)
{
var settings = loadInfo ?? new LoadSettings();
return settings.ForceChannels;
}
private static StbApi.Stb.DataType GetNativeDataType(string filePath)
{
if (StbApi.Stb.Is16Bit(filePath))
return StbApi.Stb.DataType._16Bit;
if (StbApi.Stb.IsHdr(filePath))
return StbApi.Stb.DataType.Float;
return StbApi.Stb.DataType._8Bit;
}
private static StbApi.Stb.DataType GetNativeDataType(ReadOnlySpan<byte> data)
{
if (StbApi.Stb.Is16BitFromMemory(data))
return StbApi.Stb.DataType._16Bit;
if (StbApi.Stb.IsHdrFromMemory(data))
return StbApi.Stb.DataType.Float;
return StbApi.Stb.DataType._8Bit;
}
#endregion
// The full set of formats stb_image can DECODE. This is a superset of what stb_image_write
// can ENCODE (see Stb.Writer.SupportedExtensions) - formats like .gif/.psd/.pic/.ppm/.pgm
// are load-only. stb selects its decoder from the file's content, not its extension, so this
// set only governs which extensions TextureLoader dispatches to the Stb loader.
public static FrozenSet<string> SupportedExtensions { get; } =
FrozenSet.Create(
StringComparer.OrdinalIgnoreCase,
[".png", ".jpg", ".jpeg", ".tga", ".bmp", ".hdr", ".psd", ".gif", ".pic", ".ppm", ".pgm"]
);
}

View file

@ -0,0 +1,10 @@
namespace Brutal.TextureApi.Stb;
/// <summary>
/// Thrown when the StbTextureLoaded encounters a fatal error.
/// </summary>
public class StbTextureReadException : StbTextureException
{
public StbTextureReadException(string message)
: base(message) { }
}

View file

@ -0,0 +1,158 @@
using System.Collections.Frozen;
using CommunityToolkit.HighPerformance;
namespace Brutal.TextureApi.Stb;
public class StbTextureWriteException(string message) : Exception(message);
public static partial class Writer
{
// The formats stb_image_write can ENCODE. This is the writable subset of the formats the
// Stb loader can decode (see Stb.Loader.SupportedExtensions). TextureWriter dispatches on
// this set so load-only formats are rejected at the dispatch layer rather than reaching the
// SaveToFile switch below.
public static FrozenSet<string> SupportedExtensions { get; } =
FrozenSet.Create(StringComparer.OrdinalIgnoreCase, [".png", ".jpg", ".jpeg", ".hdr", ".tga", ".bmp"]);
public static void SaveToFile(TextureDescriptor descriptor, string filePath, JpegWriteSettings? saveOptions = null)
{
SaveToFile(
filePath,
descriptor.Format.ToStbDataType(),
descriptor.Extent.X,
descriptor.Extent.Y,
NumChannels(descriptor.Format),
descriptor.Data,
saveOptions
);
}
public static void SaveToFile(ITexture texture, string filePath, JpegWriteSettings? saveInfo = null)
{
if (texture is StbTexture stbTexture)
{
SaveToFile(
filePath,
texture.Format.ToStbDataType(),
texture.Width,
texture.Height,
stbTexture.Channels,
texture.Data,
saveInfo
);
}
else
{
SaveToFile(
filePath,
texture.Format.ToStbDataType(),
texture.Width,
texture.Height,
NumChannels(texture.Format),
texture.Data,
saveInfo
);
}
}
internal static void SaveToFile(
string filePath,
StbApi.Stb.DataType dataType,
int width,
int height,
int channels,
ReadOnlySpan<byte> data,
JpegWriteSettings? saveInfo
)
{
var extension = Path.GetExtension(filePath.ToLowerInvariant().AsSpan());
ValidateDataType(dataType, extension);
bool result;
switch (extension)
{
case ".png":
{
var stride = channels * width;
result = StbApi.Stb.WritePng(filePath, width, height, channels, data, stride);
break;
}
case ".bmp":
result = StbApi.Stb.WriteBmp(filePath, width, height, channels, data);
break;
case ".tga":
result = StbApi.Stb.WriteTga(filePath, width, height, channels, data);
break;
case ".jpg" or ".jpeg":
{
var settings = saveInfo ?? JpegWriteSettings.Default;
var quality = settings.Quality;
result = StbApi.Stb.WriteJpg(filePath, width, height, channels, data, quality);
break;
}
case ".hdr":
result = StbApi.Stb.WriteHdr(filePath, width, height, channels, data.Cast<byte, float>());
break;
default:
throw new StbTextureWriteException($"Unsupported file extension {extension}");
}
if (result)
return;
var failureReason = (StbApi.Stb.TryGetFailureReason(out var reason) ? reason : "Unknown");
throw new StbTextureWriteException(
$"Failed to write texture to file at path: {filePath}, reason: {failureReason}"
);
}
private static void ValidateDataType(StbApi.Stb.DataType dataType, ReadOnlySpan<char> extension)
{
// Validate that we can write this format to the desired file type.
// Stb only supports writing from 8 bit data, with the exception of .hdr which requires float data
if (extension is ".hdr" && dataType is not StbApi.Stb.DataType.Float)
throw new StbTextureWriteException("Textures can only be saved as .hdr if they are of a float-type format");
if (dataType is not StbApi.Stb.DataType._8Bit)
throw new StbTextureWriteException(".png, .bmp, .tga, .jpg, .jpeg only support 8-bit textures");
}
public class JpegWriteSettings
{
public const int DEFAULT_QUALITY = 90;
/// <summary>
/// The quality value to use in jpeg write compression, 1 lowest => 100 highest
/// </summary>
public int Quality;
public static JpegWriteSettings Default => new() { Quality = DEFAULT_QUALITY };
}
private static int NumChannels(TextureFormat format)
{
switch (format)
{
case TextureFormat.R8_UNorm:
case TextureFormat.R16_UNorm:
case TextureFormat.R32_SFloat:
return 1;
case TextureFormat.R8G8_UNorm:
case TextureFormat.R16G16_UNorm:
case TextureFormat.R32G32_SFloat:
return 2;
case TextureFormat.R8G8B8_UNorm:
case TextureFormat.R16G16B16_UNorm:
case TextureFormat.R32G32B32_SFloat:
return 3;
case TextureFormat.R8G8B8A8_UNorm:
case TextureFormat.R16G16B16A16_UNorm:
case TextureFormat.R32G32B32A32_SFloat:
return 4;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, "TextureFormat not supported by Stb");
}
}
}