Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using DX11 = SlimDX.Direct3D11;
- using System.Runtime.InteropServices;
- namespace Rendering.HLSL
- {
- public class GlobalBufferManager
- {
- public GlobalBufferManager(GXDevice dstDevice)
- {
- mDevice = dstDevice as D3D11.GXDevice11;
- }
- public T GetGlobalBuffer<T>() where T : struct
- {
- if (mGlobalBuffers.ContainsKey(typeof(T)))
- return (T)mGlobalBuffers[typeof(T)].BufferObject;
- return CreateNewBuffer<T>();
- }
- public void UpdateGlobalBuffer<T>(T newValue) where T : struct
- {
- if (mGlobalBuffers.ContainsKey(newValue.GetType()) == false)
- throw new ArgumentException("Attempted to update a buffer that does not exist. Type: " + newValue.GetType());
- mGlobalBuffers[newValue.GetType()].BufferObject = newValue;
- SlimDX.DataStream stream = new SlimDX.DataStream(Marshal.SizeOf(newValue), true, true);
- stream.Write(newValue);
- SlimDX.DataBox box = new SlimDX.DataBox(0, 0, stream);
- mDevice.ImmediateContext.UpdateSubresource(box, mGlobalBuffers[newValue.GetType()].ConstBuffer, 0);
- if (BufferChanged != null)
- BufferChanged(typeof(T), mGlobalBuffers[newValue.GetType()]);
- }
- private T CreateNewBuffer<T>() where T : struct
- {
- var layoutAttribs = (StructLayoutAttribute[])typeof(T).GetCustomAttributes(typeof(StructLayoutAttribute), false);
- if (layoutAttribs.Length == 0 || layoutAttribs[0].Value != LayoutKind.Sequential)
- throw new ArgumentException("Attempted to create a global buffer on a struct that has not the StructLayout attribute with LayoutKind.Sequential.");
- GlobalBufferEntry entry = new GlobalBufferEntry()
- {
- BufferObject = new T(),
- ConstBuffer = new DX11.Buffer(mDevice.Device, new DX11.BufferDescription()
- {
- BindFlags = DX11.BindFlags.ConstantBuffer,
- CpuAccessFlags = DX11.CpuAccessFlags.None,
- OptionFlags = DX11.ResourceOptionFlags.None,
- SizeInBytes = Marshal.SizeOf(typeof(T)),
- StructureByteStride = 0,
- Usage = DX11.ResourceUsage.Default
- })
- };
- mGlobalBuffers.Add(typeof(T), entry);
- return (T)entry.BufferObject;
- }
- internal event Action<Type, GlobalBufferEntry> BufferChanged;
- private class GlobalBufferEntry
- {
- public object BufferObject { get; set; }
- public DX11.Buffer ConstBuffer { get; set; }
- }
- private Dictionary<Type, GlobalBufferEntry> mGlobalBuffers = new Dictionary<Type, GlobalBufferEntry>();
- private D3D11.GXDevice11 mDevice;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment