using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1Interop.__Internals;
using ComputeSharp.D2D1Interop.Extensions;
using ComputeSharp.D2D1Interop.Helpers;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
#pragma warning disable CS0618
namespace ComputeSharp.D2D1Interop.Shaders.Dispatching;
///
/// A bytecode loader for D2D1 shaders.
///
internal unsafe struct D2D1ShaderBytecodeLoader : ID2D1BytecodeLoader
{
///
/// A pointer to the precompiled shader, if available.
///
private byte* embeddedBytecodePtr;
///
/// The length of the precompiled shader buffer, if available.
///
private int embeddedBytecodeSize;
///
/// The dynamically compiled shader bytecode blob, if available.
///
private ComPtr d3DBlob;
///
/// Gets the resulting shader bytecode that was available.
///
/// The precompiled bytecode, if available.
/// An with the shader bytecode, if dynamically compiled.
/// Either is empty, or the returned pointer is .
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ComPtr GetResultingShaderBytecode(out ReadOnlySpan precompiledBytecode)
{
precompiledBytecode = new ReadOnlySpan(this.embeddedBytecodePtr, this.embeddedBytecodeSize);
return this.d3DBlob.Move();
}
///
public unsafe void LoadDynamicBytecode(IntPtr handle)
{
if (this.embeddedBytecodePtr is not null ||
this.d3DBlob.Get() is not null)
{
ThrowHelper.ThrowInvalidOperationException("The shader has already been initialized.");
}
if (handle == IntPtr.Zero)
{
ThrowHelper.ThrowNotSupportedException("Runtime shader compilation is not supported by the current configuration.");
}
this.d3DBlob = new ComPtr((ID3DBlob*)handle);
}
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void LoadEmbeddedBytecode(ReadOnlySpan bytecode)
{
if (this.embeddedBytecodePtr is not null ||
this.d3DBlob.Get() is not null)
{
ThrowHelper.ThrowInvalidOperationException("The shader has already been initialized.");
}
this.embeddedBytecodePtr = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(bytecode));
this.embeddedBytecodeSize = bytecode.Length;
}
}