diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs index 4ee092c8..85321b41 100644 --- a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs @@ -1,5 +1,6 @@ using System; using System.Buffers; +using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; using ComputeSharp.Graphics.Buffers.Enums; @@ -20,7 +21,17 @@ namespace ComputeSharp.Graphics.Buffers /// /// The associated with the current instance /// The number of items to store in the current buffer - internal ConstantBuffer(GraphicsDevice device, int size) : base(device, size, size * (Unsafe.SizeOf() / 16 + 1) * 16, BufferType.Constant) { } + internal ConstantBuffer(GraphicsDevice device, int size) : base(device, size, size * GetPaddedSize() * 16, BufferType.Constant) { } + + /// + /// Gets the right padded size for elements to store in the current instance + /// + [Pure] + private static int GetPaddedSize() + { + int size = Unsafe.SizeOf(); + return size % 16 == 0 ? 1 : size / 16 + 1; + } /// /// Gets a single value from the current constant buffer diff --git a/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs b/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs index d454a8f7..58094fdb 100644 --- a/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs +++ b/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs @@ -29,7 +29,7 @@ namespace ComputeSharp.Graphics.Buffers.Extensions void WriteValue(T value, ref byte target) where T : unmanaged { int size = Unsafe.SizeOf(); - if (offset % 16 > 16 - size) offset += 16 - offset % 16; + if (offset % 16 > 16 - size) offset += offset % 16; Unsafe.As(ref Unsafe.Add(ref target, offset)) = value; offset += size; }