using Engine.Graphics.Framebuffer;
using Engine.Graphics.Pixel;
using OpenTK.Graphics.OpenGL;
using Serilog;
namespace Engine.Graphics.Texture;
///
/// Represents a dynamic texture that can be resized and attached to a framebuffer.
///
public class DynamicTexture : Texture, IFramebufferAttachment
{
///
/// The pixel format of the texture.
///
private readonly PixelFormat _format;
///
/// The pixel type of the texture.
///
private readonly PixelType _type;
///
/// The internal format of the texture.
///
private readonly PixelInternalFormat _internalFormat;
///
/// Initializes a new instance of the class.
/// The texture is created with the specified format, type, and internal format.
///
/// The width of the texture.
/// The height of the texture.
/// The format of the texture.
/// The type of the texture.
/// The internal format of the texture.
internal DynamicTexture(int parWidth, int parHeight, PixelFormat parFormat, PixelType parType,
PixelInternalFormat parInternalFormat)
: base(parWidth, parHeight)
{
_format = parFormat;
_type = parType;
_internalFormat = parInternalFormat;
GL.BindTexture(TextureTarget.Texture2D, Handle);
GL.TexImage2D(TextureTarget.Texture2D, 0, _internalFormat, Width, Height, 0, _format, _type,
IntPtr.Zero);
}
///
/// Creates a new with the specified width, height, and pixel type.
///
/// The type of pixel used for the texture.
/// The width of the texture.
/// The height of the texture.
/// A new instance of .
public static DynamicTexture Create(int parWidth, int parHeight)
where T : struct, IPixel
{
var pixel = default(T);
return new DynamicTexture(parWidth, parHeight, pixel.Format, pixel.Type, pixel.InternalFormat);
}
///
/// Resizes the texture to the specified width and height.
///
/// The new width of the texture.
/// The new height of the texture.
public void Resize(int parWidth, int parHeight)
{
if (Width == parWidth && Height == parHeight)
{
return;
}
Width = parWidth;
Height = parHeight;
Bind();
GL.TexImage2D(TextureTarget.Texture2D, 0, _internalFormat, Width, Height, 0, _format, _type,
IntPtr.Zero);
Log.Debug("Texture {Handle} resized to {Width}x{Height}", Handle, Width, Height);
}
///
public void Attach(Framebuffer.Framebuffer parFramebuffer, FramebufferAttachment parAttachment)
{
GL.NamedFramebufferTexture(parFramebuffer.Handle, parAttachment, Handle, 0);
}
}