/// <summary> /// Function to set application specific data on the resource. /// </summary> /// <typeparam name="T">Type of data to copy into the resource. The data must be a value type.</typeparam> /// <param name="guid">GUID to associate with the data.</param> /// <param name="data">Data to set.</param> /// <remarks>Set <paramref name="data"/> to NULL (Nothing in VB.Net) to remove the data from the resource.</remarks> public void SetApplicationData <T>(Guid guid, T?data) where T : struct { IntPtr dataPtr = IntPtr.Zero; if (D3DResource == null) { return; } int bytes = DirectAccess.SizeOf <T>(); try { if (data != null) { T value = data.Value; dataPtr = Marshal.AllocHGlobal(bytes); dataPtr.Write(ref value); D3DResource.SetPrivateData(guid, bytes, dataPtr); } else { D3DResource.SetPrivateData(guid, 0, IntPtr.Zero); } } finally { if (dataPtr != IntPtr.Zero) { Marshal.FreeHGlobal(dataPtr); } } }
/// <summary> /// Function to return application specific data from the resource. /// </summary> /// <typeparam name="T">Type of data to copy into the resource. The data must be a value type.</typeparam> /// <param name="guid">GUID to associate with the data.</param> /// <returns>The application specific data stored in the resource, or NULL.</returns> public T?GetApplicationData <T>(Guid guid) where T : struct { IntPtr dataPtr = IntPtr.Zero; if (D3DResource == null) { return(null); } try { int bytes = DirectAccess.SizeOf <T>(); dataPtr = Marshal.AllocHGlobal(bytes); if (dataPtr == IntPtr.Zero) { return(null); } D3DResource.GetPrivateData(guid, ref bytes, dataPtr); T result; dataPtr.Read(out result); return(result); } finally { if (dataPtr != IntPtr.Zero) { Marshal.FreeHGlobal(dataPtr); } } }
/// <summary> /// Initializes a new instance of the <see cref="WorldViewProjection"/> class. /// </summary> /// <param name="graphics">The graphics interface to use.</param> public WorldViewProjection(GorgonGraphics graphics) { Matrix dummy = Matrix.Identity; _projViewBuffer = graphics.Buffers.CreateConstantBuffer("WVPBuffer", new GorgonConstantBufferSettings { SizeInBytes = DirectAccess.SizeOf <ViewProjectionData>(), Usage = BufferUsage.Default }); _viewProj = new ViewProjectionData { Projection = Matrix.Identity, View = Matrix.Identity, ViewProjection = Matrix.Identity }; _projViewBuffer.Update(ref _viewProj); _worldBuffer = graphics.Buffers.CreateConstantBuffer("WorldBuffer", ref dummy, BufferUsage.Default); _camData.CameraLookAt = new Vector3(0, 0, -1.0f); _camData.CameraUp = new Vector3(0, 1, 0); _cameraBuffer = graphics.Buffers.CreateConstantBuffer("CameraBuffer", ref _camData, BufferUsage.Default); graphics.Shaders.VertexShader.ConstantBuffers[0] = _projViewBuffer; graphics.Shaders.VertexShader.ConstantBuffers[1] = _worldBuffer; graphics.Shaders.PixelShader.ConstantBuffers[0] = _cameraBuffer; }
/// <summary> /// Function to create a index buffer. /// </summary> /// <param name="name">The name of the buffer.</param> /// <param name="data">Data used to initialize the buffer.</param> /// <param name="usage">[Optional] Usage of the buffer.</param> /// <param name="is32Bit">[Optional] TRUE to indicate that we're using 32 bit indices, FALSE to use 16 bit indices </param> /// <typeparam name="T">Type of data in the array. Must be a value type.</typeparam> /// <returns>A new index buffer.</returns> /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="name"/> is NULL (Nothing in VB.Net). /// <para>-or-</para> /// <para>Thrown when the <paramref name="data"/> parameter is NULL.</para> /// </exception> /// <exception cref="GorgonLibrary.GorgonException">Thrown when the buffer could not be created.</exception> /// <exception cref="System.ArgumentException">Thrown when the <paramref name="name"/> parameter is empty.</exception> /// <remarks>If creating an immutable index buffer, be sure to pre-populate it via the initialData parameter. /// <para>This method should only be called from an immediate graphics context, if it is called from a deferred context an exception will be thrown.</para> /// </remarks> public GorgonIndexBuffer CreateIndexBuffer <T>(string name, T[] data, BufferUsage usage = BufferUsage.Default, bool is32Bit = true) where T : struct { if (data == null) { throw new ArgumentNullException("data"); } if (data.Length == 0) { throw new ArgumentException(Resources.GORGFX_PARAMETER_MUST_NOT_BE_EMPTY, "data"); } int size = data.Length * DirectAccess.SizeOf <T>(); using (var dataStream = new GorgonDataStream(data)) { return(CreateIndexBuffer(name, new GorgonIndexBufferSettings { SizeInBytes = size, IsOutput = false, Usage = usage, Use32BitIndices = is32Bit }, dataStream)); } }
/// <summary> /// Function called when the effect is being initialized. /// </summary> /// <remarks> /// Use this method to set up the effect upon its creation. For example, this method could be used to create the required shaders for the effect. /// </remarks> protected override void OnInitialize() { base.OnInitialize(); _xOffsets = new Vector4[13]; _yOffsets = new Vector4[13]; _kernel = new float[13]; _blurBuffer = Graphics.ImmediateContext.Buffers.CreateConstantBuffer("Gorgon2DGaussianBlurEffect Constant Buffer", new GorgonConstantBufferSettings { SizeInBytes = DirectAccess.SizeOf <Vector4>() * _xOffsets.Length }); _blurStaticBuffer = Graphics.ImmediateContext.Buffers.CreateConstantBuffer("Gorgon2DGaussianBlurEffect Static Constant Buffer", new GorgonConstantBufferSettings { SizeInBytes = DirectAccess.SizeOf <Vector4>() * (_kernel.Length + 1) }); _blurKernelStream = new GorgonDataStream(_blurStaticBuffer.SizeInBytes); Passes[0].PixelShader = Graphics.ImmediateContext.Shaders.CreateShader <GorgonPixelShader>("Effect.PS.GaussBlur", "GorgonPixelShaderGaussBlur", "#GorgonInclude \"Gorgon2DShaders\""); UpdateKernel(); _blurSprite = Gorgon2D.Renderables.CreateSprite("Gorgon2DGaussianBlurEffect Sprite", new GorgonSpriteSettings { Size = BlurRenderTargetsSize }); _blurSprite.BlendingMode = BlendingMode.None; _blurSprite.SmoothingMode = SmoothingMode.Smooth; _blurSprite.TextureRegion = new RectangleF(0, 0, 1, 1); }
/// <summary> /// Function to register a raw input device. /// </summary> /// <param name="device">Device information.</param> /// <returns>TRUE if successful, FALSE if not.</returns> public static bool RegisterRawInputDevices(RAWINPUTDEVICE device) { var devices = new RAWINPUTDEVICE[1]; // Raw input devices. devices[0] = device; return(RegisterRawInputDevices(devices, 1, DirectAccess.SizeOf <RAWINPUTDEVICE>())); }
/// <summary> /// Function to copy the contents of a byte array into the memory pointed at by the pointer. /// </summary> /// <typeparam name="T">Type of data in the array.</typeparam> /// <param name="destination">Destination pointer.</param> /// <param name="source">Source array to copy from.</param> /// <param name="sourceIndex">Index to start copying from in the source array.</param> /// <param name="size">Number of bytes to copy.</param> /// <remarks>Since a pointer doesn't have a size associated with it, care must be taken to not overstep the bounds of the data pointed at by the pointer.</remarks> /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="source"/> parameter is NULL (Nothing in VB.Net).</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the size + sourceIndex is greater than the number of elements in the source parameter. /// <para>-or-</para> /// <para>Thrown if the sourceIndex is less than 0.</para> /// </exception> public static void CopyFrom <T>(this IntPtr destination, T[] source, int sourceIndex, int size) where T : struct { #if DEBUG int typeSize = DirectAccess.SizeOf <T>(); if (destination == IntPtr.Zero) { throw new ArgumentNullException("destination"); } if (source == null) { throw new ArgumentNullException("source"); } if (sourceIndex < 0) { throw new ArgumentOutOfRangeException("sourceIndex", string.Format(Resources.GOR_INDEX_OUT_OF_RANGE, sourceIndex, source.Length)); } if ((sourceIndex * typeSize) + size > source.Length * typeSize) { throw new ArgumentOutOfRangeException("sourceIndex", string.Format(Resources.GOR_INDEX_OUT_OF_RANGE, sourceIndex * typeSize + size, source.Length)); } #endif DirectAccess.WriteArray(destination, source, sourceIndex, size); }
/// <summary> /// Function to enumerate raw input devices. /// </summary> /// <returns>An array of raw input device structures.</returns> public unsafe static RAWINPUTDEVICELIST[] EnumerateInputDevices() { int deviceCount = 0; int structSize = DirectAccess.SizeOf <RAWINPUTDEVICELIST>(); if (GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, structSize) < 0) { throw new Win32Exception(); } if (deviceCount == 0) { return(new RAWINPUTDEVICELIST[0]); } RAWINPUTDEVICELIST *deviceListPtr = stackalloc RAWINPUTDEVICELIST[deviceCount]; if (GetRawInputDeviceList((IntPtr)deviceListPtr, ref deviceCount, structSize) < 0) { throw new Win32Exception(); } var result = new RAWINPUTDEVICELIST[deviceCount]; fixed(RAWINPUTDEVICELIST *resultPtr = &result[0]) { DirectAccess.MemoryCopy(resultPtr, deviceListPtr, structSize * deviceCount); } return(result); }
/// <summary> /// Function to update the buffer with data. /// </summary> /// <typeparam name="T">Type of data, must be a value type.</typeparam> /// <param name="values">Values to write to the buffer.</param> /// <param name="offset">Offset in the buffer, in bytes, to write at.</param> /// <param name="deferred">[Optional] The deferred context used to update the buffer.</param> /// <remarks>This method can only be used with buffers that have Default usage. Other buffer usages will thrown an exception. /// <para> /// If the <paramref name="deferred"/> parameter is NULL (Nothing in VB.Net), the immediate context will be used to update the buffer. If it is non-NULL, then it /// will use the specified deferred context. /// <para>If you are using a deferred context, it is necessary to use that context to update the buffer because 2 threads may not access the same resource at the same time. /// Passing a separate deferred context will alleviate that.</para> /// </para> /// </remarks> /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="values"/> parameter is NULL (Nothing in VB.Net).</exception> /// <exception cref="GorgonLibrary.GorgonException">Thrown when the buffer usage is not set to default.</exception> public void Update <T>(T[] values, int offset, GorgonGraphics deferred = null) where T : struct { GorgonDebug.AssertNull(values, "values"); #if DEBUG if (Settings.Usage != BufferUsage.Default) { throw new GorgonException(GorgonResult.AccessDenied, Resources.GORGFX_NOT_DEFAULT_USAGE); } #endif if (deferred == null) { deferred = Graphics; } deferred.Context.UpdateSubresource(values, D3DResource, 0, 0, 0, new D3D11.ResourceRegion { Left = offset, Right = offset + DirectAccess.SizeOf <T>() * values.Length, Top = 0, Bottom = 1, Front = 0, Back = 1 }); }
/// <summary> /// Function to copy the contents of the pointer to a byte array. /// </summary> /// <typeparam name="T">Type of data in the array.</typeparam> /// <param name="source">Source pointer.</param> /// <param name="destination">Destination array of bytes.</param> /// <param name="destinationIndex">Index in the array to start writing at.</param> /// <param name="size">Size of the data to copy, in bytes.</param> /// <remarks>Since a pointer doesn't have a size associated with it, care must be taken to not overstep the bounds of the data pointed at by the pointer.</remarks> /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="destination"/> parameter is NULL (Nothing in VB.Net).</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the size + destinationIndex is greater than the number of elements in the destination parameter. /// <para>-or-</para> /// <para>Thrown if the destinationIndex is less than 0.</para> /// </exception> public static void CopyTo <T>(this IntPtr source, T[] destination, int destinationIndex, int size) where T : struct { #if DEBUG int sizeInBytes = DirectAccess.SizeOf <T>(); if (source == IntPtr.Zero) { throw new ArgumentNullException("source"); } if (destination == null) { throw new ArgumentNullException("destination"); } if (destinationIndex < 0) { throw new ArgumentOutOfRangeException("destinationIndex", string.Format(Resources.GOR_INDEX_OUT_OF_RANGE, destinationIndex, destination.Length * sizeInBytes)); } if ((destinationIndex * sizeInBytes) + size > destination.Length * DirectAccess.SizeOf <T>()) { throw new ArgumentOutOfRangeException("destinationIndex", string.Format(Resources.GOR_INDEX_OUT_OF_RANGE, destinationIndex + size, destination.Length * sizeInBytes)); } #endif DirectAccess.ReadArray(source, destination, destinationIndex, size); }
/// <summary> /// Function to determine if this codec can read the file or not. /// </summary> /// <param name="stream">Stream used to read the file information.</param> /// <returns> /// TRUE if the codec can read the file, FALSE if not. /// </returns> /// <exception cref="System.IO.IOException">Thrown when the <paramref name="stream"/> is write-only or if the stream cannot perform seek operations.</exception> /// <exception cref="System.IO.EndOfStreamException">Thrown when an attempt to read beyond the end of the stream is made.</exception> public override bool IsReadable(Stream stream) { TGAHeader header; long position = 0; if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanRead) { throw new IOException(Resources.GORGFX_STREAM_READ_ONLY); } if (!stream.CanSeek) { throw new IOException(Resources.GORGFX_STREAM_NO_SEEK); } if (stream.Length - stream.Position < DirectAccess.SizeOf <TGAHeader>()) { return(false); } try { position = stream.Position; var reader = new GorgonBinaryReader(stream, true); header = reader.ReadValue <TGAHeader>(); } finally { stream.Position = position; } if ((header.ColorMapType != 0) || (header.ColorMapLength != 0)) { return(false); } if ((header.Descriptor & (TGADescriptor.Interleaved2Way | TGADescriptor.Interleaved4Way)) != 0) { return(false); } if ((header.Width <= 0) || (header.Height <= 0)) { return(false); } if ((header.ImageType != TGAImageType.TrueColor) && (header.ImageType != TGAImageType.TrueColorRLE) && (header.ImageType != TGAImageType.BlackAndWhite) && (header.ImageType != TGAImageType.BlackAndWhiteRLE)) { return(false); } return(((header.ImageType != TGAImageType.BlackAndWhite) && (header.ImageType != TGAImageType.BlackAndWhiteRLE)) || (header.BPP == 8)); }
/// <summary> /// Function to write a range of generic values. /// </summary> /// <typeparam name="T">Type of value to write. Must be a value type.</typeparam> /// <param name="value">Array of values to write.</param> /// <param name="startIndex">Starting index in the array.</param> /// <param name="count">Number of array elements to copy.</param> /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="value"/> parameter is NULL (Nothing in VB.Net).</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown when the <paramref name="startIndex"/> parameter is less than 0. /// <para>-or-</para> /// <para>Thrown when the startIndex parameter is equal to or greater than the number of elements in the value parameter.</para> /// <para>-or-</para> /// <para>Thrown when the sum of startIndex and <paramref name="count"/> is greater than the number of elements in the value parameter.</para> /// </exception> /// <exception cref="System.IO.IOException">Thrown when the stream is read-only.</exception> public unsafe void WriteRange <T>(T[] value, int startIndex, int count) where T : struct { if (value == null) { throw new ArgumentNullException("value"); } if ((value.Length == 0) || (count <= 0)) { return; } if (startIndex < 0) { throw new ArgumentOutOfRangeException(string.Format(Resources.GOR_VALUE_IS_LESS_THAN, startIndex, 0)); } if (startIndex >= value.Length) { throw new ArgumentOutOfRangeException(string.Format(Resources.GOR_VALUE_IS_GREATER_THAN, startIndex, value.Length)); } if (startIndex + count > value.Length) { throw new ArgumentOutOfRangeException(string.Format(Resources.GOR_VALUE_IS_LESS_THAN, startIndex + count, value.Length)); } int typeSize = DirectAccess.SizeOf <T>(); int offset = typeSize * startIndex; int size = typeSize * count; // Allocate our temporary buffer if we haven't already. if (_tempBuffer == null) { _tempBuffer = new byte[GorgonChunkedFormat.TempBufferSize]; } fixed(byte *tempBufferPointer = &_tempBuffer[0]) { while (size > 0) { int blockSize = size > GorgonChunkedFormat.TempBufferSize ? GorgonChunkedFormat.TempBufferSize : size; // Read our array into our temporary byte buffer. DirectAccess.ReadArray(tempBufferPointer, value, offset, blockSize); offset += blockSize; size -= size; // Write the temporary byte buffer to the stream. Write(_tempBuffer, 0, blockSize); } } }
/// <summary> /// Function to write a range of generic values. /// </summary> /// <typeparam name="T">Type of value to write. Must be a value type.</typeparam> /// <param name="value">Array of values to write.</param> /// <param name="startIndex">Starting index in the array.</param> /// <param name="count">Number of array elements to copy.</param> /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="value"/> parameter is NULL (Nothing in VB.Net).</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown when the <paramref name="startIndex"/> parameter is less than 0. /// <para>-or-</para> /// <para>Thrown when the startIndex parameter is equal to or greater than the number of elements in the value parameter.</para> /// <para>-or-</para> /// <para>Thrown when the sum of startIndex and <paramref name="count"/> is greater than the number of elements in the value parameter.</para> /// </exception> /// <exception cref="System.IO.IOException">Thrown when the stream is read-only.</exception> public unsafe void WriteRange <T>(T[] value, int startIndex, int count) where T : struct { ValidateAccess(true); if (value == null) { throw new ArgumentNullException("value"); } if ((value.Length == 0) || (count <= 0)) { return; } if ((startIndex < 0) || (startIndex >= value.Length)) { throw new ArgumentOutOfRangeException(string.Format(Resources.GOR_INDEX_OUT_OF_RANGE, startIndex, value.Length)); } if (startIndex + count > value.Length) { throw new ArgumentOutOfRangeException(string.Format(Resources.GOR_INDEX_OUT_OF_RANGE, startIndex + count, value.Length)); } int typeSize = DirectAccess.SizeOf <T>(); int offset = typeSize * startIndex; int size = typeSize * count; // Allocate our temporary buffer if we haven't already. if (TempBuffer == null) { TempBuffer = new byte[TempBufferSize]; } fixed(byte *tempBufferPointer = &TempBuffer[0]) { while (size > 0) { int blockSize = size > TempBufferSize ? TempBufferSize : size; // Read our array into our temporary byte buffer. DirectAccess.WriteArray(tempBufferPointer, value, offset, blockSize); offset += blockSize; size -= size; // Write the temporary byte buffer to the stream. Write(TempBuffer, 0, blockSize); } } }
/// <summary> /// Function to read a range of generic values. /// </summary> /// <typeparam name="T">Type of value to read. Must be a value type.</typeparam> /// <param name="value">Array of values to read.</param> /// <param name="startIndex">Starting index in the array.</param> /// <param name="count">Number of array elements to copy.</param> /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="value"/> parameter is NULL (Nothing in VB.Net).</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown when the <paramref name="startIndex"/> parameter is less than 0. /// <para>-or-</para> /// <para>Thrown when the startIndex parameter is equal to or greater than the number of elements in the value parameter.</para> /// <para>-or-</para> /// <para>Thrown when the sum of startIndex and <paramref name="count"/> is greater than the number of elements in the value parameter.</para> /// </exception> /// <exception cref="System.IO.IOException">Thrown when the stream is write-only.</exception> public unsafe void ReadRange <T>(T[] value, int startIndex, int count) where T : struct { if (value == null) { throw new ArgumentNullException("value"); } if ((value.Length == 0) || (count <= 0)) { return; } if (startIndex < 0) { throw new ArgumentOutOfRangeException(string.Format(Resources.GOR_VALUE_IS_LESS_THAN, startIndex, 0)); } if (startIndex >= value.Length) { throw new ArgumentOutOfRangeException(string.Format(Resources.GOR_VALUE_IS_GREATER_THAN, startIndex, value.Length)); } if (startIndex + count > value.Length) { throw new ArgumentOutOfRangeException(string.Format(Resources.GOR_VALUE_IS_LESS_THAN, startIndex + count, value.Length)); } int typeSize = DirectAccess.SizeOf <T>(); int size = typeSize * count; int offset = startIndex * typeSize; if (_tempBuffer == null) { _tempBuffer = new byte[GorgonChunkedFormat.TempBufferSize]; } fixed(byte *tempBufferPointer = &_tempBuffer[0]) { while (size > 0) { int blockSize = size > GorgonChunkedFormat.TempBufferSize ? GorgonChunkedFormat.TempBufferSize : size; // Read the data from the stream as byte values. Read(_tempBuffer, 0, blockSize); // Copy into our array. DirectAccess.ReadArray(tempBufferPointer, value, offset, blockSize); offset += blockSize; size -= blockSize; } } }
/// <summary> /// Function to copy the contents of a byte array into the memory pointed at by the pointer. /// </summary> /// <typeparam name="T">Type of data in the array.</typeparam> /// <param name="destination">Destination pointer.</param> /// <param name="source">Source array to copy from.</param> /// <remarks>Since a pointer doesn't have a size associated with it, care must be taken to not overstep the bounds of the data pointed at by the pointer.</remarks> /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="source"/> parameter is NULL (Nothing in VB.Net).</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the size + sourceIndex is greater than the number of elements in the source parameter. /// <para>-or-</para> /// <para>Thrown if the sourceIndex is less than 0.</para> /// </exception> public static void CopyFrom <T>(this IntPtr destination, T[] source) where T : struct { #if DEBUG if (source == null) { throw new ArgumentNullException("source"); } #endif CopyFrom(destination, source, 0, source.Length * DirectAccess.SizeOf <T>()); }
/// <summary> /// Function to read a range of generic values. /// </summary> /// <typeparam name="T">Type of value to read. Must be a value type.</typeparam> /// <param name="value">Array of values to read.</param> /// <param name="startIndex">Starting index in the array.</param> /// <param name="count">Number of array elements to copy.</param> /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="value"/> parameter is NULL (Nothing in VB.Net).</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown when the <paramref name="startIndex"/> parameter is less than 0. /// <para>-or-</para> /// <para>Thrown when the startIndex parameter is equal to or greater than the number of elements in the value parameter.</para> /// <para>-or-</para> /// <para>Thrown when the sum of startIndex and <paramref name="count"/> is greater than the number of elements in the value parameter.</para> /// </exception> /// <exception cref="System.IO.IOException">Thrown when the stream is write-only.</exception> public unsafe void ReadRange <T>(T[] value, int startIndex, int count) where T : struct { ValidateAccess(false); if (value == null) { throw new ArgumentNullException("value"); } if ((value.Length == 0) || (count <= 0)) { return; } if ((startIndex < 0) || (startIndex >= value.Length)) { throw new ArgumentOutOfRangeException(string.Format(Resources.GOR_INDEX_OUT_OF_RANGE, startIndex, value.Length)); } if (startIndex + count > value.Length) { throw new ArgumentOutOfRangeException(string.Format(Resources.GOR_INDEX_OUT_OF_RANGE, startIndex + count, value.Length)); } int typeSize = DirectAccess.SizeOf <T>(); int size = typeSize * count; int offset = startIndex * typeSize; if (TempBuffer == null) { TempBuffer = new byte[TempBufferSize]; } fixed(byte *tempBufferPointer = &TempBuffer[0]) { while (size > 0) { int blockSize = size > TempBufferSize ? TempBufferSize : size; // Read the data from the stream as byte values. Read(TempBuffer, 0, blockSize); // Copy into our array. DirectAccess.ReadArray(tempBufferPointer, value, offset, blockSize); offset += blockSize; size -= blockSize; } } }
/// <summary> /// Function called when the effect is being initialized. /// </summary> /// <remarks> /// Use this method to set up the effect upon its creation. For example, this method could be used to create the required shaders for the effect. /// <para>When creating a custom effect, use this method to initialize the effect. Do not put initialization code in the effect constructor.</para> /// </remarks> protected override void OnInitialize() { base.OnInitialize(); Passes[0].PixelShader = Graphics.ImmediateContext.Shaders.CreateShader <GorgonPixelShader>("Effect.2D.SobelEdgeDetect.PS", "GorgonPixelShaderSobelEdge", "#GorgonInclude \"Gorgon2DShaders\""); _sobelBuffer = Graphics.ImmediateContext.Buffers.CreateConstantBuffer("Gorgon2DSobelEdgeDetectEffect Constant Buffer", new GorgonConstantBufferSettings { SizeInBytes = DirectAccess.SizeOf <Settings>() }); _settings = new Settings(Color.Black, Vector2.Zero, 0.75f); }
/// <summary> /// Function to create a structured buffer and initialize it with data. /// </summary> /// <param name="name">The name of the structured buffer.</param> /// <param name="value">Value to write to the buffer.</param> /// <param name="usage">Usage for the buffer.</param> /// <returns>A new structured buffer.</returns> /// <typeparam name="T">Type of data to write. Must be a value type.</typeparam> /// <remarks>This method should only be called from an immediate graphics context, if it is called from a deferred context an exception will be thrown.</remarks> /// <exception cref="GorgonLibrary.GorgonException">Thrown when the buffer could not be created.</exception> public GorgonStructuredBuffer CreateStructuredBuffer <T>(string name, T value, BufferUsage usage) where T : struct { using (var stream = GorgonDataStream.ValueToStream(value)) { return(CreateStructuredBuffer(name, new GorgonStructuredBufferSettings { Usage = usage, SizeInBytes = DirectAccess.SizeOf <T>(), StructureSize = DirectAccess.SizeOf <T>() }, stream)); } }
/// <summary> /// Function called when the effect is being initialized. /// </summary> /// <remarks> /// Use this method to set up the effect upon its creation. For example, this method could be used to create the required shaders for the effect. /// <para>When creating a custom effect, use this method to initialize the effect. Do not put initialization code in the effect constructor.</para> /// </remarks> protected override void OnInitialize() { base.OnInitialize(); Passes[0].PixelShader = Graphics.ImmediateContext.Shaders.CreateShader <GorgonPixelShader>("Effect.2D.Wave.PS", "GorgonPixelShaderWaveEffect", "#GorgonInclude \"Gorgon2DShaders\""); _waveBuffer = Graphics.ImmediateContext.Buffers.CreateConstantBuffer("Gorgon2DWaveEffect Constant Buffer", new GorgonConstantBufferSettings { SizeInBytes = DirectAccess.SizeOf <Settings>() }); _settings = new Settings(10.0f, 50.0f, 0.0f, 100.0f, WaveType.Horizontal); }
/// <summary> /// Initializes a new instance of the <see cref="Sphere" /> class. /// </summary> /// <param name="graphics">Graphics interface to use.</param> /// <param name="radius">Radius of the sphere</param> /// <param name="textureCoordinates">The texture coordinates to apply to the sphere.</param> /// <param name="angle">The angle of rotation, in degrees.</param> /// <param name="ringCount">Number of rings in the sphere.</param> /// <param name="segmentCount">Number of segments in the sphere.</param> public Sphere(GorgonGraphics graphics, float radius, RectangleF textureCoordinates, Vector3 angle, int ringCount = 8, int segmentCount = 16) { Quaternion orientation; // Calculate number of vertices and indices required for our sphere. PrimitiveType = PrimitiveType.TriangleList; VertexCount = (ringCount + 1) * (segmentCount + 1); IndexCount = 6 * ringCount * (segmentCount + 1); TriangleCount = IndexCount / 3; Quaternion.RotationYawPitchRoll(angle.Y.Radians(), angle.X.Radians(), angle.Z.Radians(), out orientation); Matrix.RotationQuaternion(ref orientation, out _orientation); unsafe { using (var vertexData = new GorgonDataStream(VertexCount * Vertex3D.Size)) using (var normalData = new GorgonDataStream(VertexCount * 2 * Vector4.SizeInBytes)) using (var indexData = new GorgonDataStream(IndexCount * DirectAccess.SizeOf <int>())) { GetVertices((Vertex3D *)vertexData.UnsafePointer, (int *)indexData.UnsafePointer, normalData.UnsafePointer, radius, textureCoordinates, ringCount, segmentCount); VertexBuffer = graphics.Buffers.CreateVertexBuffer("SphereVertexBuffer", new GorgonBufferSettings { Usage = BufferUsage.Immutable, SizeInBytes = (int)vertexData.Length }, vertexData); IndexBuffer = graphics.Buffers.CreateIndexBuffer("SphereIndexBuffer", new GorgonIndexBufferSettings { Usage = BufferUsage.Immutable, Use32BitIndices = true, SizeInBytes = (int)indexData.Length }, indexData); Normals = graphics.Buffers.CreateVertexBuffer("NormalsBuffer", new GorgonBufferSettings { Usage = BufferUsage.Immutable, SizeInBytes = (int)normalData.Length }, normalData); } } }
/// <summary> /// Function to read file meta data. /// </summary> /// <param name="stream">Stream used to read the metadata.</param> /// <returns> /// The image meta data as a <see cref="GorgonLibrary.Graphics.IImageSettings">IImageSettings</see> value. /// </returns> /// <exception cref="System.IO.IOException">Thrown when the <paramref name="stream"/> is write-only or if the stream cannot perform seek operations. /// <para>-or-</para> /// <para>Thrown if the file is corrupt or can't be read by the codec.</para> /// </exception> /// <exception cref="System.IO.EndOfStreamException">Thrown when an attempt to read beyond the end of the stream is made.</exception> public override IImageSettings GetMetaData(Stream stream) { long position = 0; int headerSize = DirectAccess.SizeOf <TGAHeader>(); if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanRead) { throw new IOException(Resources.GORGFX_STREAM_WRITE_ONLY); } if (!stream.CanSeek) { throw new IOException(Resources.GORGFX_STREAM_NO_SEEK); } if (stream.Length - stream.Position < sizeof(uint) + DirectAccess.SizeOf <TGAHeader>()) { throw new EndOfStreamException(Resources.GORGFX_STREAM_EOF); } try { position = stream.Position; TGAConversionFlags conversion; var gorgonDataStream = stream as GorgonDataStream; if (gorgonDataStream != null) { return(ReadHeader(gorgonDataStream, out conversion)); } using (var memoryStream = new GorgonDataStream(headerSize)) { memoryStream.ReadFromStream(stream, headerSize); memoryStream.Position = 0; return(ReadHeader(memoryStream, out conversion)); } } finally { stream.Position = position; } }
/// <summary> /// Function to copy the contents of the pointer to a byte array. /// </summary> /// <typeparam name="T">Type of data in the array.</typeparam> /// <param name="source">Source pointer.</param> /// <param name="destination">Destination array.</param> /// <remarks>Since a pointer doesn't have a size associated with it, care must be taken to not overstep the bounds of the data pointed at by the pointer.</remarks> /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="destination"/> parameter is NULL (Nothing in VB.Net).</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the size + destinationIndex is greater than the number of elements in the destination parameter. /// <para>-or-</para> /// <para>Thrown if the destinationIndex is less than 0.</para> /// </exception> public static void CopyTo <T>(this IntPtr source, T[] destination) where T : struct { #if DEBUG if (source == IntPtr.Zero) { throw new ArgumentNullException("source"); } if (destination == null) { throw new ArgumentNullException("destination"); } #endif CopyTo(source, destination, 0, destination.Length * DirectAccess.SizeOf <T>()); }
/// <summary> /// Function to write a single value type to the buffer. /// </summary> /// <typeparam name="T">Type of value type.</typeparam> /// <param name="data">Value type data to write into the buffer.</param> /// <param name="deferred">[Optional] A deferred context to use when updating the buffer.</param> /// <remarks> /// This overload is useful for directly copying a value into the buffer without needing a data stream. If the type of value is a /// struct and contains reference types (arrays, strings, and objects), then these members will not be copied. Some form of /// marshalling will be required in order to copy structures with reference types. /// <para> /// If the <paramref name="deferred"/> parameter is NULL (Nothing in VB.Net), the immediate context will be used to update the buffer. If it is non-NULL, then it /// will use the specified deferred context to clear the render target. /// <para>If you are using a deferred context, it is necessary to use that context to update the buffer because 2 threads may not access the same resource at the same time. /// Passing a separate deferred context will alleviate that.</para> /// </para> /// <para>This will only work on buffers created with a usage type of [Default].</para> /// </remarks> /// <exception cref="GorgonLibrary.GorgonException">Thrown when the buffer does not have a usage of Default.</exception> public void Update <T>(ref T data, GorgonGraphics deferred = null) where T : struct { #if DEBUG if (Settings.Usage != BufferUsage.Default) { throw new GorgonException(GorgonResult.AccessDenied, Resources.GORGFX_NOT_DEFAULT_USAGE); } #endif if (deferred == null) { deferred = Graphics; } deferred.Context.UpdateSubresource(ref data, D3DResource, 0, DirectAccess.SizeOf <T>()); }
/// <summary> /// Function to retrieve device information. /// </summary> /// <param name="deviceHandle">Device handle.</param> /// <returns>The device information structure.</returns> public static unsafe RID_DEVICE_INFO GetDeviceInfo(IntPtr deviceHandle) { int dataSize = DirectAccess.SizeOf <RID_DEVICE_INFO>(); byte *data = stackalloc byte[dataSize]; if (GetRawInputDeviceInfo(deviceHandle, RawInputCommand.DeviceInfo, (IntPtr)data, ref dataSize) < 0) { throw new Win32Exception(); } RID_DEVICE_INFO result; DirectAccess.MemoryCopy(&result, data, dataSize); return(result); }
/// <summary> /// Function called when the effect is being initialized. /// </summary> /// <remarks> /// Use this method to set up the effect upon its creation. For example, this method could be used to create the required shaders for the effect. /// <para>When creating a custom effect, use this method to initialize the effect. Do not put initialization code in the effect constructor.</para> /// </remarks> protected override void OnInitialize() { base.OnInitialize(); _point = Gorgon2D.Renderables.CreatePoint("Effect.OldFilm.DustPoint", Vector2.Zero, GorgonColor.Black); // Create pixel shader. Passes[0].PixelShader = Graphics.Shaders.CreateShader <GorgonPixelShader>("Effect.OldFilm.PS", "GorgonPixelShaderFilmGrain", Encoding.UTF8.GetString(Resources.FilmGrain)); _timingBuffer = Graphics.Buffers.CreateConstantBuffer("Effect.OldFilm.TimingBuffer", new GorgonConstantBufferSettings { SizeInBytes = 16 }); _scratchBuffer = Graphics.Buffers.CreateConstantBuffer("Effect.OldFilm.ScratchSettingsBuffer", new GorgonConstantBufferSettings { SizeInBytes = DirectAccess.SizeOf <ScratchSettings>() }); _sepiaBuffer = Graphics.Buffers.CreateConstantBuffer("Effect.OldFilm.SepaSettingsBuffer", new GorgonConstantBufferSettings { SizeInBytes = DirectAccess.SizeOf <SepiaSettings>() }); DirtPercent = 5; DirtAmount = 10; _scratchSettings = new ScratchSettings { ScratchIntensity = 0.49f, ScratchScrollSpeed = 0.01f, ScratchVisibleTime = 0.003f, ScratchWidth = 0.01f }; _sepiaSettings = new SepiaSettings { SepiaDesaturationAmount = 0.0f, SepiaToneAmount = 0.5f, SepiaLightColor = new GorgonColor(1, 0.9f, 0.65f, 1.0f), SepiaDarkColor = new GorgonColor(0.2f, 0.102f, 0, 1.0f) }; }
/// <summary> /// Function to write an array of value types to the buffer. /// </summary> /// <typeparam name="T">Type of value type.</typeparam> /// <param name="data">Value type data to write into the buffer.</param> /// <param name="deferred">[Optional] A deferred context to use when updating the buffer.</param> /// <remarks> /// This overload is useful for directly copying values into the buffer without needing a data stream. If the type of value is a /// struct and contains reference types (arrays, strings, and objects), then these members will not be copied. Some form of /// marshalling will be required in order to copy structures with reference types. /// <para> /// If the <paramref name="deferred" /> parameter is NULL (Nothing in VB.Net), the immediate context will be used to update the buffer. If it is non-NULL, then it /// will use the specified deferred context to clear the render target. /// <para>If you are using a deferred context, it is necessary to use that context to update the buffer because 2 threads may not access the same resource at the same time. /// Passing a separate deferred context will alleviate that.</para> /// </para> /// <para>This will only work on buffers created with a usage type of [Default].</para> /// </remarks> public override void Update <T>(T[] data, GorgonGraphics deferred = null) { GorgonDebug.AssertNull(data, "data"); #if DEBUG if (Settings.Usage != BufferUsage.Default) { throw new GorgonException(GorgonResult.AccessDenied, Resources.GORGFX_NOT_DEFAULT_USAGE); } #endif if (deferred == null) { deferred = Graphics; } deferred.Context.UpdateSubresource(data, D3DResource, 0, DirectAccess.SizeOf <T>() * data.Length); }
/// <summary> /// Initializes a new instance of the <see cref="Gorgon2DPixelShaderState"/> class. /// </summary> /// <param name="gorgon2D">The gorgon 2D interface that created this object.</param> internal Gorgon2DPixelShaderState(Gorgon2D gorgon2D) : base(gorgon2D.Graphics) { _gorgon2D = gorgon2D; DefaultPixelShaderDiffuse = Graphics.ImmediateContext.Shaders.CreateShader <GorgonPixelShader>("Default_Basic_Pixel_Shader_Diffuse", "GorgonPixelShaderDiffuse", "#GorgonInclude \"Gorgon2DShaders\""); DefaultPixelShaderTextured = Graphics.ImmediateContext.Shaders.CreateShader <GorgonPixelShader>("Default_Basic_Pixel_Shader_Texture", "GorgonPixelShaderTextured", "#GorgonInclude \"Gorgon2DShaders\""); DefaultPixelShaderDiffuseMaterial = Graphics.ImmediateContext.Shaders.CreateShader <GorgonPixelShader>( "Default_Basic_Pixel_Shader_Diffuse_Material", "GorgonPixelShaderDiffuseMaterial", "#GorgonInclude \"Gorgon2DShaders\""); DefaultPixelShaderTexturedMaterial = Graphics.ImmediateContext.Shaders.CreateShader <GorgonPixelShader>( "Default_Basic_Pixel_Shader_Texture_Material", "GorgonPixelShaderTexturedMaterial", "#GorgonInclude \"Gorgon2DShaders\""); var alphaTestValues = new Gorgon2DAlphaTest(gorgon2D.IsAlphaTestEnabled, GorgonRangeF.Empty); AlphaTestValuesBuffer = Graphics.ImmediateContext.Buffers.CreateConstantBuffer("Gorgon2D Alpha Test Constant Buffer", new GorgonConstantBufferSettings { SizeInBytes = DirectAccess.SizeOf <Gorgon2DAlphaTest>() }); // Initialize the alpha testing values. AlphaTestValuesBuffer.Update(ref alphaTestValues); MaterialBuffer = Graphics.ImmediateContext.Buffers.CreateConstantBuffer("Gorgon2D Material Constant Buffer", new GorgonConstantBufferSettings { SizeInBytes = 32, Usage = BufferUsage.Default }); }
/// <summary> /// Function to reset the timer. /// </summary> public void Reset() { TIMECAPS caps = default(TIMECAPS); if (_isHighResTimer) { if (Win32API.QueryPerformanceFrequency(out _frequency)) { Win32API.QueryPerformanceCounter(out _startTime); return; } _isHighResTimer = false; } if (_timePeriod > 0) { if (Win32API.timeEndPeriod(_timePeriod) == TimePeriodReturn.NoCanDo) { throw new Win32Exception(Resources.GOR_TIME_CANNOT_END); } } else { if (Win32API.timeGetDevCaps(ref caps, DirectAccess.SizeOf <TIMECAPS>()) != 0) { throw new Win32Exception(Resources.GOR_TIME_CANNOT_BEGIN); } _timePeriod = caps.MinPeriod; } if (Win32API.timeBeginPeriod(_timePeriod) == TimePeriodReturn.NoCanDo) { throw new Win32Exception(Resources.GOR_TIME_CANNOT_BEGIN); } UsingLowResTimers = true; _startTick = Environment.TickCount; _startTime = Win32API.timeGetTime(); }
/// <summary> /// Function to write an array of value types to the buffer. /// </summary> /// <typeparam name="T">Type of value type.</typeparam> /// <param name="data">Value type data to write into the buffer.</param> /// <param name="deferred">[Optional] A deferred context to use when updating the buffer.</param> /// <remarks> /// This overload is useful for directly copying values into the buffer without needing a data stream. If the type of value is a /// struct and contains reference types (arrays, strings, and objects), then these members will not be copied. Some form of /// marshalling will be required in order to copy structures with reference types. /// <para> /// If the <paramref name="deferred"/> parameter is NULL (Nothing in VB.Net), the immediate context will be used to update the buffer. If it is non-NULL, then it /// will use the specified deferred context to clear the render target. /// <para>If you are using a deferred context, it is necessary to use that context to update the buffer because 2 threads may not access the same resource at the same time. /// Passing a separate deferred context will alleviate that.</para> /// </para> /// <para>This will only work on buffers created with a usage type of [Default].</para> /// </remarks> /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="data"/> parameter is NULL (Nothing in VB.Net).</exception> /// <exception cref="GorgonLibrary.GorgonException">Thrown when the buffer does not have a usage of Default.</exception> public virtual void Update <T>(T[] data, GorgonGraphics deferred = null) where T : struct { GorgonDebug.AssertNull(data, "data"); #if DEBUG if (Settings.Usage != BufferUsage.Default) { throw new GorgonException(GorgonResult.AccessDenied, Resources.GORGFX_NOT_DEFAULT_USAGE); } #endif if (deferred == null) { deferred = Graphics; } deferred.Context.UpdateSubresource(data, D3DResource, 0, DirectAccess.SizeOf <T>() * data.Length, 0, new D3D.ResourceRegion(0, 0, 0, SizeInBytes, 1, 1)); }
/// <summary> /// Function to create a constant buffer and initializes it with data. /// </summary> /// <typeparam name="T">Type of data to pass to the constant buffer. Must be a value type.</typeparam> /// <param name="name">The name of the constant buffer.</param> /// <param name="value">Value to write to the buffer</param> /// <param name="usage">Usage for the buffer.</param> /// <returns>A new constant buffer.</returns> /// <remarks>This method should only be called from an immediate graphics context, if it is called from a deferred context an exception will be thrown.</remarks> /// <exception cref="System.ArgumentNullException">Thrown when the <paramref name="name"/> parameter is NULL (Nothing in VB.Net).</exception> /// <exception cref="System.ArgumentException">Thrown when the <paramref name="name"/> parameter is empty.</exception> /// <exception cref="GorgonLibrary.GorgonException">Thrown when the buffer could not be created.</exception> public GorgonConstantBuffer CreateConstantBuffer <T>(string name, ref T value, BufferUsage usage) where T : struct { int size = DirectAccess.SizeOf <T>(); // Ensure the total size of the object is a multiple of 16. while ((size % 16) != 0) { size++; } var result = CreateConstantBuffer(name, new GorgonConstantBufferSettings { Usage = usage, SizeInBytes = size }); result.Update(ref value); return(result); }