using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; namespace ComputeSharp.D2D1.Interop; /// /// Provides an ID2D1ResourceTextureManager implementation, which can be used to manage resources in /// an effect created with and share them across multiple effect instances. /// /// /// /// The built-in ID2D1EffectImpl /// implementation provided by (which makes it possible to register and create /// ID2D1Effect /// instances that can be used to run D2D1 pixel shaders) uses resource texture manager objects to handle resource textures. /// /// /// These managers are COM objects implementing the following interface: /// /// [uuid(3C4FC7E4-A419-46CA-B5F6-66EB4FF18D64)] /// interface ID2D1ResourceTextureManager : IUnknown /// { /// HRESULT Initialize( /// [in, optional] const GUID *resourceId, /// [in] const D2D1_RESOURCE_TEXTURE_PROPERTIES *resourceTextureProperties, /// [in, optional] const BYTE *data, /// [in, optional] const UINT32 *strides, /// UINT32 dataSize); /// /// HRESULT Update( /// [in, optional] const UINT32 *minimumExtents, /// [in, optional] const UINT32 *maximimumExtents, /// [in] const UINT32 *strides, /// UINT32 dimensions, /// [in] const BYTE *data, /// UINT32 dataCount); /// }; /// /// /// /// These can be used to create resource textures, pass them to effects, and also share resources among different effects. /// /// /// For details of how these work, Initialize maps to /// ID2D1EffectContext::CreateResourceTexture, /// whereas Update maps to ID2D1ResourceTexture::Update. /// The same behavior and parameters as those methods is used. /// /// /// This interface is implemented by ComputeSharp.D2D1, and it can be used through the APIs in . /// That is, is first used to create an ID2D1ResourceTextureManager instance. Then, /// can be used to initialize the resource texture held by the manager. The manager can also be assigned to an effect at any time, /// using the available property indices from . To update texture data after its initial /// creation, can be used. /// /// /// An RCW (runtime callable wrapper, see ), /// is also available for all of these APIs, implemented by the same . In this case, the constructor can /// be used to create and initialize an instance (equivalent to calling and ), and then /// is available for texture data updates. /// The instance implements , which can be used in advanced scenarios to retrieve the underlying COM object. /// /// /// The ID2D1ResourceTextureManager contract allows callers to create a resource texture at any time even before the effect /// has been initialized and the manager assigned to it. In that case, the manager will buffer the data internally, and will defer /// the creation of the actual resource texture until it's possible for it to do so, at which point it will also free the buffer. /// /// /// If implementing a custom resource manager is needed, in order for external implementations to be accepted by the effect objects /// created by , the ID2D1ResourceTextureManagerInternal interface also needs to be implemented: /// /// [uuid(5CBB1024-8EA1-4689-81BF-8AD190B5EF5D)] /// interface ID2D1ResourceTextureManager : IUnknown /// { /// HRESULT Initialize( /// [in] ID2D1EffectContext *effectContext, /// [in, optional] const UINT32 *dimensions); /// /// HRESULT GetResourceTexture([out] ID2D1ResourceTexture **resourceTexture); /// }; /// /// /// /// Note that due to the fact ID2D1EffectContext /// and ID2D1ResourceTexture are not thread safe, /// they are only safe to use without additional synchronization when Initialize and GetResourceTexture are called. This happens from the internal /// ID2D1EffectImpl object, which is invoked by D2D, which will handle /// taking the necessary lock before invoking these APIs. Due to the fact the context has to be stored internally, custom implementations have to make sure to retrieve the /// right ID2D1Multithread instance from the effect context and use that to synchronize all accesses to those two objects from all APIs (including those exposed by /// ID2D1ResourceTextureManager). The built-in implementation of these two interfaces provided by takes care of all this. /// /// /// The dimensions parameter in ID2D1ResourceTextureManager::Initialize is optional, and can be passed by an ID2D1Effect /// when initializing an input resurce texture manager, if the dimensions of the resource texture at the target index are known in advance. /// This can allow the manager to perform additional validation when the resource texture is initialized. Not providing a value is not an /// error, but if a resource texture with invalid size is used the effect might fail to render later on and be more difficult to troubleshoot. /// /// public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface { /// /// The object wrapped by the current instance. /// private readonly D2D1ResourceTextureManagerImpl* d2D1ResourceManagerImpl; /// /// Creates a new instance with the specified parameters. /// /// The extents of the resource to create. /// The buffer precision for the resource to create. /// The channel depth for the resource to create. /// The filter for the resource to create. /// The extend modes for the resource to create. /// Thrown if creating or initializing the instance failed. public D2D1ResourceTextureManager( ReadOnlySpan extents, D2D1BufferPrecision bufferPrecision, D2D1ChannelDepth channelDepth, D2D1Filter filter, ReadOnlySpan extendModes) : this( null, extents, bufferPrecision, channelDepth, filter, extendModes, ReadOnlySpan.Empty, ReadOnlySpan.Empty) { } /// /// Creates a new instance with the specified parameters. /// /// The resource id for the resource to create. /// The extents of the resource to create. /// The buffer precision for the resource to create. /// The channel depth for the resource to create. /// The filter for the resource to create. /// The extend modes for the resource to create. /// Thrown if creating or initializing the instance failed. public D2D1ResourceTextureManager( Guid resourceId, ReadOnlySpan extents, D2D1BufferPrecision bufferPrecision, D2D1ChannelDepth channelDepth, D2D1Filter filter, ReadOnlySpan extendModes) : this( &resourceId, extents, bufferPrecision, channelDepth, filter, extendModes, ReadOnlySpan.Empty, ReadOnlySpan.Empty) { } /// /// Creates a new instance with the specified parameters. /// /// The extents of the resource to create. /// The buffer precision for the resource to create. /// The channel depth for the resource to create. /// The filter for the resource to create. /// The extend modes for the resource to create. /// The data to load in the resource to create. /// The strides for the data supplied for the resource to create. /// Thrown if creating or initializing the instance failed. public D2D1ResourceTextureManager( ReadOnlySpan extents, D2D1BufferPrecision bufferPrecision, D2D1ChannelDepth channelDepth, D2D1Filter filter, ReadOnlySpan extendModes, ReadOnlySpan data, ReadOnlySpan strides) : this( null, extents, bufferPrecision, channelDepth, filter, extendModes, data, strides) { } /// /// Creates a new instance with the specified parameters. /// /// The resource id for the resource to create. /// The extents of the resource to create. /// The buffer precision for the resource to create. /// The channel depth for the resource to create. /// The filter for the resource to create. /// The extend modes for the resource to create. /// The data to load in the resource to create. /// The strides for the data supplied for the resource to create. /// Thrown if creating or initializing the instance failed. public D2D1ResourceTextureManager( Guid resourceId, ReadOnlySpan extents, D2D1BufferPrecision bufferPrecision, D2D1ChannelDepth channelDepth, D2D1Filter filter, ReadOnlySpan extendModes, ReadOnlySpan data, ReadOnlySpan strides) : this( &resourceId, extents, bufferPrecision, channelDepth, filter, extendModes, data, strides) { } /// /// Creates a new instance with the specified parameters. /// /// The resource id for the resource to create. /// The extents of the resource to create. /// The buffer precision for the resource to create. /// The channel depth for the resource to create. /// The filter for the resource to create. /// The extend modes for the resource to create. /// The data to load in the resource to create. /// The strides for the data supplied for the resource to create. /// Thrown if creating or initializing the instance failed. private D2D1ResourceTextureManager( Guid* resourceId, ReadOnlySpan extents, D2D1BufferPrecision bufferPrecision, D2D1ChannelDepth channelDepth, D2D1Filter filter, ReadOnlySpan extendModes, ReadOnlySpan data, ReadOnlySpan strides) { // Manually validate the parameters here to ensure the native objects wouldn't try // to read out of bounds and potentially AV. For those cases, we just throw here. if (extents.Length == 0 || extendModes.Length == 0 || extents.Length != extendModes.Length || (data.Length > 0 && strides.Length != extents.Length - 1)) { GC.SuppressFinalize(this); Marshal.ThrowExceptionForHR(E.E_INVALIDARG); } fixed (D2D1ResourceTextureManagerImpl** d2D1ResourceManagerImpl = &this.d2D1ResourceManagerImpl) { D2D1ResourceTextureManagerImpl.Factory(d2D1ResourceManagerImpl); } fixed (uint* pExtents = extents) fixed (D2D1ExtendMode* pExtendModes = extendModes) fixed (byte* pData = data) fixed (uint* pStrides = strides) { D2D1_RESOURCE_TEXTURE_PROPERTIES d2D1ResourceTextureProperties; d2D1ResourceTextureProperties.extents = pExtents; d2D1ResourceTextureProperties.dimensions = (uint)extents.Length; d2D1ResourceTextureProperties.bufferPrecision = (D2D1_BUFFER_PRECISION)bufferPrecision; d2D1ResourceTextureProperties.channelDepth = (D2D1_CHANNEL_DEPTH)channelDepth; d2D1ResourceTextureProperties.filter = (D2D1_FILTER)filter; d2D1ResourceTextureProperties.extendModes = (D2D1_EXTEND_MODE*)pExtendModes; int hresult = D2D1ResourceTextureManagerImpl.Initialize( @this: this.d2D1ResourceManagerImpl, resourceId: resourceId, resourceTextureProperties: &d2D1ResourceTextureProperties, data: pData, strides: pStrides, dataSize: (uint)data.Length); Marshal.ThrowExceptionForHR(hresult); } } /// /// Releases the underlying ID2D1ResourceTextureManager object. /// ~D2D1ResourceTextureManager() { if (this.d2D1ResourceManagerImpl is not null) { this.d2D1ResourceManagerImpl->Release(); } } /// /// Updates the specific resource texture inside the specific range or box using the supplied data. /// /// The "left" extent of the updates if specified. If , the entire texture is updated. /// The "right" extent of the updates if specified. If , the entire texture is updated. /// The stride to advance through the input data, according to dimension. /// The data to be placed into the resource texture. public void Update( ReadOnlySpan minimumExtents, ReadOnlySpan maximimumExtents, ReadOnlySpan strides, ReadOnlySpan data) { fixed (uint* pMinimumExtents = minimumExtents) fixed (uint* pMaximumExtents = maximimumExtents) fixed (uint* pStrides = strides) fixed (byte* pData = data) { int dimensions = strides.Length + 1; // Ensure that if the extents are not null, their length is correct. This is again to // avoid the native method assuming they'd be longer than they are and causing an AV. if (pMinimumExtents is not null && pMaximumExtents is not null && (minimumExtents.Length != dimensions || maximimumExtents.Length != dimensions)) { Marshal.ThrowExceptionForHR(E.E_INVALIDARG); } int hresult = D2D1ResourceTextureManagerImpl.Update( @this: this.d2D1ResourceManagerImpl, minimumExtents: pMinimumExtents, maximimumExtents: pMaximumExtents, strides: pStrides, dimensions: (uint)dimensions, data: pData, dataCount: (uint)data.Length); GC.KeepAlive(this); Marshal.ThrowExceptionForHR(hresult); } } /// /// Gets the underlying object. /// /// The underlying object. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void GetD2D1ResourceTextureManager(ID2D1ResourceTextureManager** resourceTextureManager) { _ = this.d2D1ResourceManagerImpl->AddRef(); *resourceTextureManager = (ID2D1ResourceTextureManager*)this.d2D1ResourceManagerImpl; GC.KeepAlive(this); } /// CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) { fixed (Guid* pIid = &iid) fixed (IntPtr* pPpv = &ppv) { int hresult = this.d2D1ResourceManagerImpl->QueryInterface(pIid, (void**)pPpv); GC.KeepAlive(this); return hresult switch { S.S_OK => CustomQueryInterfaceResult.Handled, _ => CustomQueryInterfaceResult.Failed }; } } /// /// Creates a new ID2D1ResourceTextureManager instance. /// /// A pointer to the resulting ID2D1ResourceTextureManager instance. public static void Create(void** resourceTextureManager) { D2D1ResourceTextureManagerImpl.Factory((D2D1ResourceTextureManagerImpl**)resourceTextureManager); } /// /// Initializes a given ID2D1ResourceTextureManager instance. /// /// A pointer to the ID2D1ResourceTextureManager instance to use. /// The resource id for the resource to create. /// The extents of the resource to create. /// The buffer precision for the resource to create. /// The channel depth for the resource to create. /// The filter for the resource to create. /// The extend modes for the resource to create. /// The data to load in the resource to create. /// The strides for the data supplied for the resource to create. /// /// Depending on internal state, might immediately create the resource /// texture, or it might buffer the data internally and then create the resource texture at a later time. /// public static void Initialize( void* resourceTextureManager, Guid resourceId, ReadOnlySpan extents, D2D1BufferPrecision bufferPrecision, D2D1ChannelDepth channelDepth, D2D1Filter filter, ReadOnlySpan extendModes, ReadOnlySpan data, ReadOnlySpan strides) { // Validate parameters early from here too to avoid AVs in the native method if (extents.Length == 0 || extendModes.Length == 0 || extents.Length != extendModes.Length || (data.Length > 0 && strides.Length != extents.Length - 1)) { Marshal.ThrowExceptionForHR(E.E_INVALIDARG); } fixed (uint* pExtents = extents) fixed (D2D1ExtendMode* pExtendModes = extendModes) fixed (byte* pData = data) fixed (uint* pStrides = strides) { D2D1_RESOURCE_TEXTURE_PROPERTIES d2D1ResourceTextureProperties; d2D1ResourceTextureProperties.extents = pExtents; d2D1ResourceTextureProperties.dimensions = (uint)extents.Length; d2D1ResourceTextureProperties.bufferPrecision = (D2D1_BUFFER_PRECISION)bufferPrecision; d2D1ResourceTextureProperties.channelDepth = (D2D1_CHANNEL_DEPTH)channelDepth; d2D1ResourceTextureProperties.filter = (D2D1_FILTER)filter; d2D1ResourceTextureProperties.extendModes = (D2D1_EXTEND_MODE*)pExtendModes; int hresult = ((ID2D1ResourceTextureManager*)resourceTextureManager)->Initialize( resourceId: &resourceId, resourceTextureProperties: &d2D1ResourceTextureProperties, data: pData, strides: pStrides, dataSize: (uint)data.Length); Marshal.ThrowExceptionForHR(hresult); } } /// /// Updates the data in a given ID2D1ResourceTextureManager instance. /// /// A pointer to the ID2D1ResourceTextureManager instance to use. /// The "left" extent of the updates if specified (if empty, the entire texture is updated). /// The "right" extent of the updates if specified (if empty, the entire texture is updated). /// The stride to advance through the input data. /// The data to be placed into the resource texture. public static void Update( void* resourceTextureManager, ReadOnlySpan minimumExtents, ReadOnlySpan maximimumExtents, ReadOnlySpan strides, ReadOnlySpan data) { fixed (uint* pMinimumExtents = minimumExtents) fixed (uint* pMaximumExtents = maximimumExtents) fixed (uint* pStrides = strides) fixed (byte* pData = data) { int dimensions = strides.Length + 1; // Same validation as in the Update instance method above if (pMinimumExtents is not null && pMaximumExtents is not null && (minimumExtents.Length != dimensions || maximimumExtents.Length != dimensions)) { Marshal.ThrowExceptionForHR(E.E_INVALIDARG); } int hresult = ((ID2D1ResourceTextureManager*)resourceTextureManager)->Update( minimumExtents: pMinimumExtents, maximimumExtents: pMaximumExtents, strides: pStrides, dimensions: (uint)dimensions, data: pData, dataCount: (uint)data.Length); Marshal.ThrowExceptionForHR(hresult); } } }