MoonWorks/src/Graphics/GraphicsResource.cs

77 lines
2.1 KiB
C#
Raw Normal View History

using System;
using System.Runtime.InteropServices;
namespace MoonWorks.Graphics
{
2022-02-23 05:14:32 +00:00
public abstract class GraphicsResource : IDisposable
{
public GraphicsDevice Device { get; }
2022-12-13 08:52:35 +00:00
public IntPtr Handle { get; internal set; }
2022-02-23 05:14:32 +00:00
public bool IsDisposed { get; private set; }
2022-03-04 01:16:39 +00:00
protected abstract Action<IntPtr, IntPtr> QueueDestroyFunction { get; }
2023-11-21 01:09:22 +00:00
private GCHandle SelfReference;
2023-11-21 01:09:22 +00:00
protected GraphicsResource(GraphicsDevice device)
2022-02-23 05:14:32 +00:00
{
Device = device;
2023-11-21 01:09:22 +00:00
SelfReference = GCHandle.Alloc(this, GCHandleType.Weak);
Device.AddResourceReference(SelfReference);
}
2023-11-21 01:09:22 +00:00
private GraphicsResourceDisposalHandle CreateDisposalHandle()
{
return new GraphicsResourceDisposalHandle
{
QueueDestroyAction = QueueDestroyFunction,
ResourceHandle = Handle
};
2022-02-23 05:14:32 +00:00
}
2023-11-21 01:09:22 +00:00
protected void Dispose(bool disposing)
2022-02-23 05:14:32 +00:00
{
if (!IsDisposed)
{
if (Handle != IntPtr.Zero)
2022-02-23 05:14:32 +00:00
{
2022-03-04 01:16:39 +00:00
QueueDestroyFunction(Device.Handle, Handle);
2023-11-21 01:09:22 +00:00
Device.RemoveResourceReference(SelfReference);
SelfReference.Free();
Handle = IntPtr.Zero;
2022-02-23 05:14:32 +00:00
}
IsDisposed = true;
}
}
~GraphicsResource()
{
#if DEBUG
2023-11-21 01:09:22 +00:00
// If the graphics device associated with this resource was already disposed, we assume
// that your game is in the middle of shutting down.
if (!IsDisposed && Device != null && !Device.IsDisposed)
{
// If you see this log message, you leaked a graphics resource without disposing it!
// This means your game may eventually run out of native memory for mysterious reasons.
Logger.LogWarn($"A resource of type {GetType().Name} was not Disposed.");
}
#endif
// While we only log in debug builds, in both debug and release builds we want to free
// any native resources associated with this object at the earliest opportunity.
// This will at least prevent you from running out of memory rapidly.
Device.RegisterForEmergencyDisposal(CreateDisposalHandle());
2022-02-23 05:14:32 +00:00
}
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}