commit 18fd14e1974966b16beef11085602323fa732664 Author: BlubbFish Date: Sun Nov 15 22:13:50 2015 +0000 openclnet hinzugefügt diff --git a/OpenCLNet.sln b/OpenCLNet.sln new file mode 100644 index 0000000..d4a6036 --- /dev/null +++ b/OpenCLNet.sln @@ -0,0 +1,102 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenCLNet", "OpenCLNet\OpenCLNet.csproj", "{758285C6-1ACA-458A-9906-EE6701D5AF87}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenCLTest", "examples\OpenCLTest\OpenCLTest.csproj", "{68E39C68-7A11-4AF8-9FEA-3147E720D96D}" +EndProject +Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "OpenCLVBTest", "examples\OpenCLVBTest\OpenCLVBTest.vbproj", "{397E0A3D-6B9B-4718-8DA2-421AA5EF8864}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitTests", "UnitTests\UnitTests.csproj", "{264E13EF-4308-4033-96C1-54C13C82D7C0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageCrossFade", "examples\ImageCrossFade\ImageCrossFade.csproj", "{F7D24581-6EA3-4D20-A722-1BACC34B94AA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenCLImageTest", "examples\OpenCLImageTest\OpenCLImageTest.csproj", "{64E8D6E8-B245-47E4-BA61-9BD000E187FA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {758285C6-1ACA-458A-9906-EE6701D5AF87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {758285C6-1ACA-458A-9906-EE6701D5AF87}.Debug|Any CPU.Build.0 = Debug|Any CPU + {758285C6-1ACA-458A-9906-EE6701D5AF87}.Debug|x64.ActiveCfg = Debug|x64 + {758285C6-1ACA-458A-9906-EE6701D5AF87}.Debug|x64.Build.0 = Debug|x64 + {758285C6-1ACA-458A-9906-EE6701D5AF87}.Debug|x86.ActiveCfg = Debug|x86 + {758285C6-1ACA-458A-9906-EE6701D5AF87}.Debug|x86.Build.0 = Debug|x86 + {758285C6-1ACA-458A-9906-EE6701D5AF87}.Release|Any CPU.ActiveCfg = Release|Any CPU + {758285C6-1ACA-458A-9906-EE6701D5AF87}.Release|Any CPU.Build.0 = Release|Any CPU + {758285C6-1ACA-458A-9906-EE6701D5AF87}.Release|x64.ActiveCfg = Release|x64 + {758285C6-1ACA-458A-9906-EE6701D5AF87}.Release|x64.Build.0 = Release|x64 + {758285C6-1ACA-458A-9906-EE6701D5AF87}.Release|x86.ActiveCfg = Release|x86 + {758285C6-1ACA-458A-9906-EE6701D5AF87}.Release|x86.Build.0 = Release|x86 + {68E39C68-7A11-4AF8-9FEA-3147E720D96D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {68E39C68-7A11-4AF8-9FEA-3147E720D96D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {68E39C68-7A11-4AF8-9FEA-3147E720D96D}.Debug|x64.ActiveCfg = Debug|x64 + {68E39C68-7A11-4AF8-9FEA-3147E720D96D}.Debug|x64.Build.0 = Debug|x64 + {68E39C68-7A11-4AF8-9FEA-3147E720D96D}.Debug|x86.ActiveCfg = Debug|x86 + {68E39C68-7A11-4AF8-9FEA-3147E720D96D}.Debug|x86.Build.0 = Debug|x86 + {68E39C68-7A11-4AF8-9FEA-3147E720D96D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {68E39C68-7A11-4AF8-9FEA-3147E720D96D}.Release|Any CPU.Build.0 = Release|Any CPU + {68E39C68-7A11-4AF8-9FEA-3147E720D96D}.Release|x64.ActiveCfg = Release|x64 + {68E39C68-7A11-4AF8-9FEA-3147E720D96D}.Release|x64.Build.0 = Release|x64 + {68E39C68-7A11-4AF8-9FEA-3147E720D96D}.Release|x86.ActiveCfg = Release|x86 + {68E39C68-7A11-4AF8-9FEA-3147E720D96D}.Release|x86.Build.0 = Release|x86 + {397E0A3D-6B9B-4718-8DA2-421AA5EF8864}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {397E0A3D-6B9B-4718-8DA2-421AA5EF8864}.Debug|Any CPU.Build.0 = Debug|Any CPU + {397E0A3D-6B9B-4718-8DA2-421AA5EF8864}.Debug|x64.ActiveCfg = Debug|x64 + {397E0A3D-6B9B-4718-8DA2-421AA5EF8864}.Debug|x64.Build.0 = Debug|x64 + {397E0A3D-6B9B-4718-8DA2-421AA5EF8864}.Debug|x86.ActiveCfg = Debug|x86 + {397E0A3D-6B9B-4718-8DA2-421AA5EF8864}.Debug|x86.Build.0 = Debug|x86 + {397E0A3D-6B9B-4718-8DA2-421AA5EF8864}.Release|Any CPU.ActiveCfg = Release|Any CPU + {397E0A3D-6B9B-4718-8DA2-421AA5EF8864}.Release|Any CPU.Build.0 = Release|Any CPU + {397E0A3D-6B9B-4718-8DA2-421AA5EF8864}.Release|x64.ActiveCfg = Release|x64 + {397E0A3D-6B9B-4718-8DA2-421AA5EF8864}.Release|x64.Build.0 = Release|x64 + {397E0A3D-6B9B-4718-8DA2-421AA5EF8864}.Release|x86.ActiveCfg = Release|x86 + {397E0A3D-6B9B-4718-8DA2-421AA5EF8864}.Release|x86.Build.0 = Release|x86 + {264E13EF-4308-4033-96C1-54C13C82D7C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {264E13EF-4308-4033-96C1-54C13C82D7C0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {264E13EF-4308-4033-96C1-54C13C82D7C0}.Debug|x64.ActiveCfg = Debug|x64 + {264E13EF-4308-4033-96C1-54C13C82D7C0}.Debug|x64.Build.0 = Debug|x64 + {264E13EF-4308-4033-96C1-54C13C82D7C0}.Debug|x86.ActiveCfg = Debug|x86 + {264E13EF-4308-4033-96C1-54C13C82D7C0}.Debug|x86.Build.0 = Debug|x86 + {264E13EF-4308-4033-96C1-54C13C82D7C0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {264E13EF-4308-4033-96C1-54C13C82D7C0}.Release|Any CPU.Build.0 = Release|Any CPU + {264E13EF-4308-4033-96C1-54C13C82D7C0}.Release|x64.ActiveCfg = Release|x64 + {264E13EF-4308-4033-96C1-54C13C82D7C0}.Release|x64.Build.0 = Release|x64 + {264E13EF-4308-4033-96C1-54C13C82D7C0}.Release|x86.ActiveCfg = Release|x86 + {264E13EF-4308-4033-96C1-54C13C82D7C0}.Release|x86.Build.0 = Release|x86 + {F7D24581-6EA3-4D20-A722-1BACC34B94AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F7D24581-6EA3-4D20-A722-1BACC34B94AA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F7D24581-6EA3-4D20-A722-1BACC34B94AA}.Debug|x64.ActiveCfg = Debug|x64 + {F7D24581-6EA3-4D20-A722-1BACC34B94AA}.Debug|x64.Build.0 = Debug|x64 + {F7D24581-6EA3-4D20-A722-1BACC34B94AA}.Debug|x86.ActiveCfg = Debug|x86 + {F7D24581-6EA3-4D20-A722-1BACC34B94AA}.Debug|x86.Build.0 = Debug|x86 + {F7D24581-6EA3-4D20-A722-1BACC34B94AA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F7D24581-6EA3-4D20-A722-1BACC34B94AA}.Release|Any CPU.Build.0 = Release|Any CPU + {F7D24581-6EA3-4D20-A722-1BACC34B94AA}.Release|x64.ActiveCfg = Release|x64 + {F7D24581-6EA3-4D20-A722-1BACC34B94AA}.Release|x64.Build.0 = Release|x64 + {F7D24581-6EA3-4D20-A722-1BACC34B94AA}.Release|x86.ActiveCfg = Release|x86 + {F7D24581-6EA3-4D20-A722-1BACC34B94AA}.Release|x86.Build.0 = Release|x86 + {64E8D6E8-B245-47E4-BA61-9BD000E187FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {64E8D6E8-B245-47E4-BA61-9BD000E187FA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {64E8D6E8-B245-47E4-BA61-9BD000E187FA}.Debug|x64.ActiveCfg = Debug|x64 + {64E8D6E8-B245-47E4-BA61-9BD000E187FA}.Debug|x64.Build.0 = Debug|x64 + {64E8D6E8-B245-47E4-BA61-9BD000E187FA}.Debug|x86.ActiveCfg = Debug|x86 + {64E8D6E8-B245-47E4-BA61-9BD000E187FA}.Debug|x86.Build.0 = Debug|x86 + {64E8D6E8-B245-47E4-BA61-9BD000E187FA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {64E8D6E8-B245-47E4-BA61-9BD000E187FA}.Release|Any CPU.Build.0 = Release|Any CPU + {64E8D6E8-B245-47E4-BA61-9BD000E187FA}.Release|x64.ActiveCfg = Release|x64 + {64E8D6E8-B245-47E4-BA61-9BD000E187FA}.Release|x64.Build.0 = Release|x64 + {64E8D6E8-B245-47E4-BA61-9BD000E187FA}.Release|x86.ActiveCfg = Release|x86 + {64E8D6E8-B245-47E4-BA61-9BD000E187FA}.Release|x86.Build.0 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/OpenCLNet/AlignedArray.cs b/OpenCLNet/AlignedArray.cs new file mode 100644 index 0000000..16b4527 --- /dev/null +++ b/OpenCLNet/AlignedArray.cs @@ -0,0 +1,385 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; + +namespace OpenCLNet +{ + + unsafe public class AlignedArray where T : struct + { + protected IntPtr UnmanagedMemory; + protected IntPtr AlignedMemory; + + public long Length { get; protected set; } + public long ByteLength { get; protected set; } + protected long ByteAlignment; + protected long AlignedArraySize; + protected int TStride = Marshal.SizeOf( typeof( T ) ); + + // Track whether Dispose has been called. + private bool disposed = false; + + public AlignedArray( long size, long byteAlignment ) + { + long alignmentMask; + + Length = size; + ByteLength = size*TStride; + AlignedArraySize = size*TStride; + ByteAlignment = byteAlignment; + UnmanagedMemory = Marshal.AllocHGlobal( new IntPtr( AlignedArraySize+byteAlignment-1 ) ); + alignmentMask = ByteAlignment-1; + AlignedMemory = new IntPtr( (UnmanagedMemory.ToInt64()+byteAlignment-1)&~alignmentMask ); + } + + ~AlignedArray() + { + Dispose( false ); + } + + #region IDisposable Members + + // Implement IDisposable. + // Do not make this method virtual. + // A derived class should not be able to override this method. + public void Dispose() + { + Dispose( true ); + // This object will be cleaned up by the Dispose method. + // Therefore, you should call GC.SupressFinalize to + // take this object off the finalization queue + // and prevent finalization code for this object + // from executing a second time. + GC.SuppressFinalize( this ); + } + + // Dispose(bool disposing) executes in two distinct scenarios. + // If disposing equals true, the method has been called directly + // or indirectly by a user's code. Managed and unmanaged resources + // can be disposed. + // If disposing equals false, the method has been called by the + // runtime from inside the finalizer and you should not reference + // other objects. Only unmanaged resources can be disposed. + private void Dispose( bool disposing ) + { + // Check to see if Dispose has already been called. + if( !this.disposed ) + { + // If disposing equals true, dispose all managed + // and unmanaged resources. + if( disposing ) + { + // Dispose managed resources. + } + + // Call the appropriate methods to clean up + // unmanaged resources here. + // If disposing is false, + // only the following code is executed. + Marshal.FreeHGlobal( UnmanagedMemory ); + + // Note disposing has been done. + disposed = true; + } + } + + #endregion + } + + + #region AlignedArrayByte + + /// + /// Aligned 1D array class for bytes + /// + unsafe public class AlignedArrayByte : AlignedArray + { + byte* pAlignedArray; + + public AlignedArrayByte( long size, long byteAlignment ) + : base( size, byteAlignment ) + { + pAlignedArray = (byte*)AlignedMemory.ToPointer(); + } + + public IntPtr GetPtr( long index ) + { + if( index>=Length || index<0 ) + throw new IndexOutOfRangeException(); + + return new IntPtr( pAlignedArray+index ); + } + + public void Extract( long index, byte[] destinationArray, long destinationIndex, long length ) + { + if( index+length>Length || index+length<0 ) + throw new IndexOutOfRangeException(); + + for( long i=0; iLength || index+length<0 ) + throw new IndexOutOfRangeException(); + + for( long i=0; iLength ) + throw new IndexOutOfRangeException(); + + return pAlignedArray[index]; + } + set + { + if( index<0 || index>Length ) + throw new IndexOutOfRangeException(); + + pAlignedArray[index] = value; + } + } + + public static implicit operator IntPtr( AlignedArrayByte array ) + { + return new IntPtr( array.pAlignedArray ); + } + } + + #endregion + + #region AlignedArrayInt + + /// + /// Aligned 1D array class for ints + /// + unsafe public class AlignedArrayInt : AlignedArray + { + int* pAlignedArray; + + public AlignedArrayInt(long size, long byteAlignment) + : base(size, byteAlignment) + { + pAlignedArray = (int*)AlignedMemory.ToPointer(); + } + + public IntPtr GetPtr(long index) + { + if (index >= Length || index < 0) + throw new IndexOutOfRangeException(); + + return new IntPtr(pAlignedArray + index); + } + + public void Extract(long index, int[] destinationArray, long destinationIndex, long length) + { + if (index + length > Length || index + length < 0) + throw new IndexOutOfRangeException(); + + for (long i = 0; i < length; i++) + destinationArray[destinationIndex + i] = pAlignedArray[index + i]; + } + + public void Insert(long index, int[] sourceArray, long sourceIndex, long length) + { + if (index + length > Length || index + length < 0) + throw new IndexOutOfRangeException(); + + for (long i = 0; i < length; i++) + pAlignedArray[index + i] = sourceArray[sourceIndex + i]; + } + + public int this[long index] + { + get + { + if (index < 0 || index > Length) + throw new IndexOutOfRangeException(); + + return pAlignedArray[index]; + } + set + { + if (index < 0 || index > Length) + throw new IndexOutOfRangeException(); + + pAlignedArray[index] = value; + } + } + + public static implicit operator IntPtr(AlignedArrayInt array) + { + return new IntPtr(array.pAlignedArray); + } + } + + #endregion + + #region AlignedArrayLong + + /// + /// Aligned 1D array class for longs + /// + unsafe public class AlignedArrayLong : AlignedArray + { + long* pAlignedArray; + + public AlignedArrayLong(long size, long byteAlignment) + : base(size, byteAlignment) + { + pAlignedArray = (long*)AlignedMemory.ToPointer(); + } + + public IntPtr GetPtr(long index) + { + if (index >= Length || index < 0) + throw new IndexOutOfRangeException(); + + return new IntPtr(pAlignedArray + index); + } + + public void Extract(long index, long[] destinationArray, long destinationIndex, long length) + { + if (index + length > Length || index + length < 0) + throw new IndexOutOfRangeException(); + + for (long i = 0; i < length; i++) + destinationArray[destinationIndex + i] = pAlignedArray[index + i]; + } + + public void Insert(long index, long[] sourceArray, long sourceIndex, long length) + { + if (index + length > Length || index + length < 0) + throw new IndexOutOfRangeException(); + + for (long i = 0; i < length; i++) + pAlignedArray[index + i] = sourceArray[sourceIndex + i]; + } + + public long this[long index] + { + get + { + if (index < 0 || index > Length) + throw new IndexOutOfRangeException(); + + return pAlignedArray[index]; + } + set + { + if (index < 0 || index > Length) + throw new IndexOutOfRangeException(); + + pAlignedArray[index] = value; + } + } + + public static implicit operator IntPtr(AlignedArrayLong array) + { + return new IntPtr(array.pAlignedArray); + } + } + + #endregion + + #region AlignedArrayFloat + + /// + /// Aligned 1D array class for floats + /// + unsafe public class AlignedArrayFloat : AlignedArray + { + float* pAlignedArray; + + public AlignedArrayFloat(long size, long byteAlignment) + : base(size, byteAlignment) + { + pAlignedArray = (float*)AlignedMemory.ToPointer(); + } + + public IntPtr GetPtr(long index) + { + if (index >= Length || index < 0) + throw new IndexOutOfRangeException(); + + return new IntPtr(pAlignedArray + index); + } + + public void Extract(long index, float[] destinationArray, long destinationIndex, long length) + { + if (index + length > Length || index + length < 0) + throw new IndexOutOfRangeException(); + + for (long i = 0; i < length; i++) + destinationArray[destinationIndex + i] = pAlignedArray[index + i]; + } + + public void Insert(long index, float[] sourceArray, long sourceIndex, long length) + { + if (index + length > Length || index + length < 0) + throw new IndexOutOfRangeException(); + + for (long i = 0; i < length; i++) + pAlignedArray[index + i] = sourceArray[sourceIndex + i]; + } + + public float this[long index] + { + get + { + if (index < 0 || index > Length) + throw new IndexOutOfRangeException(); + + return pAlignedArray[index]; + } + set + { + if (index < 0 || index > Length) + throw new IndexOutOfRangeException(); + + pAlignedArray[index] = value; + } + } + + public static implicit operator IntPtr(AlignedArrayFloat array) + { + return new IntPtr(array.pAlignedArray); + } + } + + #endregion + +} diff --git a/OpenCLNet/CommandQueue.cs b/OpenCLNet/CommandQueue.cs new file mode 100644 index 0000000..90b27a7 --- /dev/null +++ b/OpenCLNet/CommandQueue.cs @@ -0,0 +1,1229 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Text; + +namespace OpenCLNet +{ + /// + /// The CommandQueue class wraps an OpenCL command queue reference. + /// + /// This class contains methods that correspond to all OpenCL functions that take + /// a command queue as their first parameter. Most notably, all the Enqueue() functions. + /// In effect, it makes this class into the workhorse of most OpenCL applications. + /// + unsafe public class CommandQueue : IDisposable + { + public IntPtr CommandQueueID { get; private set; } + public Context Context { get; private set; } + public Device Device { get; private set; } + public uint ReferenceCount { get { return 0; } } + public CommandQueueProperties Properties { get { return (CommandQueueProperties)0; } } + + // Track whether Dispose has been called. + private bool disposed = false; + + #region Construction / Destruction + + internal CommandQueue( Context context, Device device, IntPtr commandQueueID ) + { + Context = context; + Device = device; + CommandQueueID = commandQueueID; + } + + // Use C# destructor syntax for finalization code. + // This destructor will run only if the Dispose method + // does not get called. + // It gives your base class the opportunity to finalize. + // Do not provide destructors in types derived from this class. + ~CommandQueue() + { + // Do not re-create Dispose clean-up code here. + // Calling Dispose(false) is optimal in terms of + // readability and maintainability. + Dispose( false ); + } + + #endregion + + #region IDisposable Members + + // Implement IDisposable. + // Do not make this method virtual. + // A derived class should not be able to override this method. + public void Dispose() + { + Dispose( true ); + // This object will be cleaned up by the Dispose method. + // Therefore, you should call GC.SupressFinalize to + // take this object off the finalization queue + // and prevent finalization code for this object + // from executing a second time. + GC.SuppressFinalize( this ); + } + + // Dispose(bool disposing) executes in two distinct scenarios. + // If disposing equals true, the method has been called directly + // or indirectly by a user's code. Managed and unmanaged resources + // can be disposed. + // If disposing equals false, the method has been called by the + // runtime from inside the finalizer and you should not reference + // other objects. Only unmanaged resources can be disposed. + private void Dispose( bool disposing ) + { + // Check to see if Dispose has already been called. + if( !this.disposed ) + { + // If disposing equals true, dispose all managed + // and unmanaged resources. + if( disposing ) + { + // Dispose managed resources. + } + + // Call the appropriate methods to clean up + // unmanaged resources here. + // If disposing is false, + // only the following code is executed. + OpenCL.ReleaseCommandQueue( CommandQueueID ); + CommandQueueID = IntPtr.Zero; + + // Note disposing has been done. + disposed = true; + } + } + + #endregion + + // Enqueue methods follow. Typically, each will have 3 versions. + // One which takes an event wait list and and event output + // One which takes an event wait list + // and one which takes neither + + #region EnqueueWriteBuffer + + /// + /// Enqueues a command to write data to a buffer object identified by buffer from host memory identified by ptr. + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void EnqueueWriteBuffer(Mem buffer, bool blockingWrite, IntPtr offset, IntPtr cb, IntPtr ptr, int numEventsInWaitList, Event[] event_wait_list, out Event _event) + { + ErrorCode result; + IntPtr tmpEvent; + + result = OpenCL.EnqueueWriteBuffer(CommandQueueID, + buffer.MemID, + (uint)(blockingWrite ? Bool.TRUE : Bool.FALSE), + offset, + cb, + ptr.ToPointer(), + (uint)numEventsInWaitList, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent); + _event = new Event( Context, tmpEvent ); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueReadBuffer failed with error code " + result, result); + } + public void EnqueueWriteBuffer(Mem buffer, bool blockingWrite, IntPtr offset, IntPtr cb, IntPtr ptr, int numEventsInWaitList, Event[] event_wait_list) + { + ErrorCode result; + + result = OpenCL.EnqueueWriteBuffer(CommandQueueID, + buffer.MemID, + (uint)(blockingWrite ? Bool.TRUE : Bool.FALSE), + offset, + cb, + ptr.ToPointer(), + (uint)numEventsInWaitList, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueReadBuffer failed with error code " + result, result); + } + public void EnqueueWriteBuffer(Mem buffer, bool blockingWrite, IntPtr offset, IntPtr cb, IntPtr ptr) + { + ErrorCode result; + + result = OpenCL.EnqueueWriteBuffer(CommandQueueID, + buffer.MemID, + (uint)(blockingWrite ? Bool.TRUE : Bool.FALSE), + offset, + cb, + ptr.ToPointer(), + (uint)0, + null, + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueReadBuffer failed with error code " + result, result); + } + #endregion + + #region EnqueueReadBuffer + + /// + /// Enqueues a command to read data from a buffer object identified by buffer to host memory identified by ptr. + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void EnqueueReadBuffer(Mem buffer, bool blockingRead, IntPtr offset, IntPtr cb, IntPtr ptr, int numEventsInWaitList, Event[] event_wait_list, out Event _event) + { + ErrorCode result; + IntPtr tmpEvent; + + result = OpenCL.EnqueueReadBuffer(CommandQueueID, + buffer.MemID, + (uint)(blockingRead ? Bool.TRUE : Bool.FALSE), + offset, + cb, + ptr.ToPointer(), + (uint)numEventsInWaitList, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent); + _event = new Event(Context, tmpEvent); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueReadBuffer failed with error code " + result, result); + } + + public void EnqueueReadBuffer(Mem buffer, bool blockingRead, IntPtr offset, IntPtr cb, IntPtr ptr, int numEventsInWaitList, Event[] event_wait_list ) + { + ErrorCode result; + + result = OpenCL.EnqueueReadBuffer(CommandQueueID, + buffer.MemID, + (uint)(blockingRead ? Bool.TRUE : Bool.FALSE), + offset, + cb, + ptr.ToPointer(), + (uint)numEventsInWaitList, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueReadBuffer failed with error code " + result, result); + } + + public void EnqueueReadBuffer(Mem buffer, bool blockingRead, IntPtr offset, IntPtr cb, IntPtr ptr) + { + ErrorCode result; + + result = OpenCL.EnqueueReadBuffer(CommandQueueID, + buffer.MemID, + (uint)(blockingRead ? Bool.TRUE : Bool.FALSE), + offset, + cb, + ptr.ToPointer(), + (uint)0, + null, + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueReadBuffer failed with error code " + result, result); + } + + #endregion + + #region EnqueueCopyBuffer + + /// + /// Enqueues a command to copy a buffer object identified by src_buffer to another buffer object identified by dst_buffer. + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void EnqueueCopyBuffer(Mem src_buffer, Mem dst_buffer, IntPtr src_offset, IntPtr dst_offset, IntPtr cb, int num_events_in_wait_list, Event[] event_wait_list, out Event _event) + { + ErrorCode result; + IntPtr tmpEvent; + + result = OpenCL.EnqueueCopyBuffer(CommandQueueID, + src_buffer.MemID, + dst_buffer.MemID, + src_offset, + dst_offset, + cb, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent); + _event = new Event(Context, tmpEvent); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueCopyBuffer failed with error code " + result, result); + } + + public void EnqueueCopyBuffer(Mem src_buffer, Mem dst_buffer, IntPtr src_offset, IntPtr dst_offset, IntPtr cb, int num_events_in_wait_list, Event[] event_wait_list) + { + ErrorCode result; + + result = OpenCL.EnqueueCopyBuffer(CommandQueueID, + src_buffer.MemID, + dst_buffer.MemID, + src_offset, + dst_offset, + cb, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueCopyBuffer failed with error code " + result, result); + } + + public void EnqueueCopyBuffer(Mem src_buffer, Mem dst_buffer, IntPtr src_offset, IntPtr dst_offset, IntPtr cb) + { + ErrorCode result; + + result = OpenCL.EnqueueCopyBuffer(CommandQueueID, + src_buffer.MemID, + dst_buffer.MemID, + src_offset, + dst_offset, + cb, + (uint)0, + null, + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueCopyBuffer failed with error code " + result, result); + } + + #endregion + + #region EnqueueReadImage + + public void EnqueueReadImage(Mem image, bool blockingRead, IntPtr[] origin, IntPtr[] region, IntPtr row_pitch, IntPtr slice_pitch, void* ptr, int num_events_in_wait_list, Event[] event_wait_list, out Event _event) + { + ErrorCode result; + IntPtr tmpEvent; + + result = OpenCL.EnqueueReadImage(CommandQueueID, + image.MemID, + (uint)(blockingRead ? Bool.TRUE : Bool.FALSE), + origin, + region, + row_pitch, + slice_pitch, + ptr, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent); + _event = new Event(Context, tmpEvent); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueReadImage failed with error code " + result, result); + } + + public void EnqueueReadImage(Mem image, bool blockingRead, IntPtr[] origin, IntPtr[] region, IntPtr row_pitch, IntPtr slice_pitch, void* ptr, int num_events_in_wait_list, Event[] event_wait_list) + { + ErrorCode result; + + result = OpenCL.EnqueueReadImage(CommandQueueID, + image.MemID, + (uint)(blockingRead ? Bool.TRUE : Bool.FALSE), + origin, + region, + row_pitch, + slice_pitch, + ptr, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueReadImage failed with error code " + result, result); + } + + public void EnqueueReadImage(Mem image, bool blockingRead, IntPtr[] origin, IntPtr[] region, IntPtr row_pitch, IntPtr slice_pitch, void* ptr) + { + ErrorCode result; + + result = OpenCL.EnqueueReadImage(CommandQueueID, + image.MemID, + (uint)(blockingRead ? Bool.TRUE : Bool.FALSE), + origin, + region, + row_pitch, + slice_pitch, + ptr, + (uint)0, + null, + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueReadImage failed with error code " + result, result); + } + + #endregion + + #region EnqueueWriteImage + + public void EnqueueWriteImage(Mem image, bool blockingWrite, IntPtr[] origin, IntPtr[] region, IntPtr input_row_pitch, IntPtr input_slice_pitch, void* ptr, int num_events_in_wait_list, Event[] event_wait_list, out Event _event) + { + ErrorCode result; + IntPtr tmpEvent; + + result = OpenCL.EnqueueWriteImage(CommandQueueID, + image.MemID, + (uint)(blockingWrite ? Bool.TRUE : Bool.FALSE), + origin, + region, + input_row_pitch, + input_slice_pitch, + ptr, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent); + _event = new Event(Context, tmpEvent); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueWriteImage failed with error code " + result, result); + } + + public void EnqueueWriteImage(Mem image, bool blockingWrite, IntPtr[] origin, IntPtr[] region, IntPtr input_row_pitch, IntPtr input_slice_pitch, void* ptr, int num_events_in_wait_list, Event[] event_wait_list) + { + ErrorCode result; + + result = OpenCL.EnqueueWriteImage(CommandQueueID, + image.MemID, + (uint)(blockingWrite ? Bool.TRUE : Bool.FALSE), + origin, + region, + input_row_pitch, + input_slice_pitch, + ptr, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueWriteImage failed with error code " + result, result); + } + + public void EnqueueWriteImage(Mem image, bool blockingWrite, IntPtr[] origin, IntPtr[] region, IntPtr input_row_pitch, IntPtr input_slice_pitch, void* ptr) + { + ErrorCode result; + + result = OpenCL.EnqueueWriteImage(CommandQueueID, + image.MemID, + (uint)(blockingWrite ? Bool.TRUE : Bool.FALSE), + origin, + region, + input_row_pitch, + input_slice_pitch, + ptr, + (uint)0, + null, + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueWriteImage failed with error code " + result, result); + } + + #endregion + + #region EnqueueCopyImage + + public void EnqueueCopyImage(Mem src_image, Mem dst_image, IntPtr[] src_origin, IntPtr[] dst_origin, IntPtr[] region, int num_events_in_wait_list, Event[] event_wait_list, out Event _event) + { + ErrorCode result; + IntPtr tmpEvent; + + result = OpenCL.EnqueueCopyImage(CommandQueueID, + src_image.MemID, + dst_image.MemID, + src_origin, + dst_origin, + region, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent); + _event = new Event(Context, tmpEvent); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueCopyImage failed with error code " + result, result); + } + + public void EnqueueCopyImage(Mem src_image, Mem dst_image, IntPtr[] src_origin, IntPtr[] dst_origin, IntPtr[] region, int num_events_in_wait_list, Event[] event_wait_list) + { + ErrorCode result; + + result = OpenCL.EnqueueCopyImage(CommandQueueID, + src_image.MemID, + dst_image.MemID, + src_origin, + dst_origin, + region, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueCopyImage failed with error code " + result, result); + } + + public void EnqueueCopyImage(Mem src_image, Mem dst_image, IntPtr[] src_origin, IntPtr[] dst_origin, IntPtr[] region) + { + ErrorCode result; + + result = OpenCL.EnqueueCopyImage(CommandQueueID, + src_image.MemID, + dst_image.MemID, + src_origin, + dst_origin, + region, + (uint)0, + null, + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueCopyImage failed with error code " + result, result); + } + + #endregion + + #region EnqueueCopyImageToBuffer + + public void EnqueueCopyImageToBuffer(Mem src_image, Mem dst_buffer, IntPtr[] src_origin, IntPtr[] region, IntPtr dst_offset, int num_events_in_wait_list, Event[] event_wait_list, out Event _event) + { + ErrorCode result; + IntPtr tmpEvent; + + result = OpenCL.EnqueueCopyImageToBuffer(CommandQueueID, + src_image.MemID, + dst_buffer.MemID, + src_origin, + region, + dst_offset, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent); + _event = new Event(Context, tmpEvent); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueCopyImageToBuffer failed with error code " + result, result); + } + + public void EnqueueCopyImageToBuffer(Mem src_image, Mem dst_buffer, IntPtr[] src_origin, IntPtr[] region, IntPtr dst_offset, int num_events_in_wait_list, Event[] event_wait_list) + { + ErrorCode result; + + result = OpenCL.EnqueueCopyImageToBuffer(CommandQueueID, + src_image.MemID, + dst_buffer.MemID, + src_origin, + region, + dst_offset, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueCopyImageToBuffer failed with error code " + result, result); + } + + public void EnqueueCopyImageToBuffer(Mem src_image, Mem dst_buffer, IntPtr[] src_origin, IntPtr[] region, IntPtr dst_offset) + { + ErrorCode result; + + result = OpenCL.EnqueueCopyImageToBuffer(CommandQueueID, + src_image.MemID, + dst_buffer.MemID, + src_origin, + region, + dst_offset, + (uint)0, + null, + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueCopyImageToBuffer failed with error code " + result, result); + } + + #endregion + + #region EnqueueCopyBufferToImage + + public void EnqueueCopyBufferToImage(Mem src_buffer, Mem dst_image, IntPtr src_offset, IntPtr[] dst_origin, IntPtr[] region, int num_events_in_wait_list, Event[] event_wait_list, out Event _event) + { + ErrorCode result; + IntPtr tmpEvent; + + result = OpenCL.EnqueueCopyBufferToImage(CommandQueueID, + src_buffer.MemID, + dst_image.MemID, + src_offset, + dst_origin, + region, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent); + _event = new Event(Context, tmpEvent); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueCopyBufferToImage failed with error code " + result, result); + } + + public void EnqueueCopyBufferToImage(Mem src_buffer, Mem dst_image, IntPtr src_offset, IntPtr[] dst_origin, IntPtr[] region, int num_events_in_wait_list, Event[] event_wait_list) + { + ErrorCode result; + + result = OpenCL.EnqueueCopyBufferToImage(CommandQueueID, + src_buffer.MemID, + dst_image.MemID, + src_offset, + dst_origin, + region, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueCopyBufferToImage failed with error code " + result, result); + } + + public void EnqueueCopyBufferToImage(Mem src_buffer, Mem dst_image, IntPtr src_offset, IntPtr[] dst_origin, IntPtr[] region) + { + ErrorCode result; + + result = OpenCL.EnqueueCopyBufferToImage(CommandQueueID, + src_buffer.MemID, + dst_image.MemID, + src_offset, + dst_origin, + region, + (uint)0, + null, + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueCopyBufferToImage failed with error code " + result, result); + } + + #endregion + + #region EnqueueMapBuffer + + public IntPtr EnqueueMapBuffer(Mem buffer, bool blockingMap, MapFlags map_flags, IntPtr offset, IntPtr cb, int num_events_in_wait_list, Event[] event_wait_list, out Event _event) + { + ErrorCode result; + IntPtr ptr; + IntPtr tmpEvent; + + ptr = (IntPtr)OpenCL.EnqueueMapBuffer(CommandQueueID, + buffer.MemID, + (uint)(blockingMap ? Bool.TRUE : Bool.FALSE), + (ulong)map_flags, + offset, + cb, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent, + out result); + _event = new Event(Context, tmpEvent); + + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueMapBuffer failed with error code " + result, result); + return ptr; + } + + public IntPtr EnqueueMapBuffer(Mem buffer, bool blockingMap, MapFlags map_flags, IntPtr offset, IntPtr cb, int num_events_in_wait_list, Event[] event_wait_list) + { + ErrorCode result; + IntPtr ptr; + + ptr = (IntPtr)OpenCL.EnqueueMapBuffer(CommandQueueID, + buffer.MemID, + (uint)(blockingMap ? Bool.TRUE : Bool.FALSE), + (ulong)map_flags, + offset, + cb, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + null, + out result); + + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueMapBuffer failed with error code " + result, result); + return ptr; + } + + public IntPtr EnqueueMapBuffer(Mem buffer, bool blockingMap, MapFlags map_flags, IntPtr offset, IntPtr cb) + { + ErrorCode result; + IntPtr ptr; + + ptr = (IntPtr)OpenCL.EnqueueMapBuffer(CommandQueueID, + buffer.MemID, + (uint)(blockingMap ? Bool.TRUE : Bool.FALSE), + (ulong)map_flags, + offset, + cb, + (uint)0, + null, + null, + out result); + + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueMapBuffer failed with error code " + result, result); + return ptr; + } + + #endregion + + #region EnqueueMapImage + + /// + /// Map the memory of a Mem object into host memory. + /// This function must be used before native code accesses an area of memory that's under the control + /// of OpenCL. This includes Mem objects allocated with MemFlags.USE_HOST_PTR, as results may be cached + /// in another location. Mapping will ensure caches are synchronizatized. + /// + /// Mem object to map + /// Flag that indicates if the operation is synchronous or not + /// Read/Write flags + /// origin contains the x,y,z coordinates indicating the starting point to map + /// origin contains the width,height,depth coordinates indicating the size of the area to map + /// + /// + /// + /// + /// + /// + /// + public IntPtr EnqueueMapImage(Mem image, bool blockingMap, MapFlags map_flags, IntPtr[] origin, IntPtr[] region, out IntPtr image_row_pitch, out IntPtr image_slice_pitch, int num_events_in_wait_list, Event[] event_wait_list, out Event _event, out ErrorCode result) + { + IntPtr ptr; + IntPtr tmpEvent; + + ptr = (IntPtr)OpenCL.EnqueueMapImage(CommandQueueID, + image.MemID, + (uint)(blockingMap ? Bool.TRUE : Bool.FALSE), + (ulong)map_flags, + origin, + region, + out image_row_pitch, + out image_slice_pitch, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent, + out result); + _event = new Event(Context, tmpEvent); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueMapImage failed with error code " + result, result); + return ptr; + } + + public IntPtr EnqueueMapImage(Mem image, bool blockingMap, MapFlags map_flags, IntPtr[] origin, IntPtr[] region, out IntPtr image_row_pitch, out IntPtr image_slice_pitch, int num_events_in_wait_list, Event[] event_wait_list, out ErrorCode result) + { + IntPtr ptr; + + ptr = (IntPtr)OpenCL.EnqueueMapImage(CommandQueueID, + image.MemID, + (uint)(blockingMap ? Bool.TRUE : Bool.FALSE), + (ulong)map_flags, + origin, + region, + out image_row_pitch, + out image_slice_pitch, + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + null, + out result); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueMapImage failed with error code " + result, result); + return ptr; + } + + public IntPtr EnqueueMapImage(Mem image, bool blockingMap, MapFlags map_flags, IntPtr[] origin, IntPtr[] region, out IntPtr image_row_pitch, out IntPtr image_slice_pitch, out ErrorCode result) + { + IntPtr ptr; + + ptr = (IntPtr)OpenCL.EnqueueMapImage(CommandQueueID, + image.MemID, + (uint)(blockingMap ? Bool.TRUE : Bool.FALSE), + (ulong)map_flags, + origin, + region, + out image_row_pitch, + out image_slice_pitch, + (uint)0, + null, + null, + out result); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueMapImage failed with error code " + result, result); + return ptr; + } + + #endregion + + #region EnqueueUnmapMemObject + + /// + /// Unmap a previously mapped Mem object + /// + /// + /// + /// + /// + /// + public void EnqueueUnmapMemObject(Mem memobj, IntPtr mapped_ptr, int num_events_in_wait_list, Event[] event_wait_list, out Event _event) + { + ErrorCode result; + IntPtr tmpEvent; + + result = OpenCL.EnqueueUnmapMemObject(CommandQueueID, + memobj.MemID, + mapped_ptr.ToPointer(), + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent); + _event = new Event(Context, tmpEvent); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueUnmapMemObject failed with error code " + result, result); + } + + public void EnqueueUnmapMemObject(Mem memobj, IntPtr mapped_ptr, int num_events_in_wait_list, Event[] event_wait_list) + { + ErrorCode result; + + result = OpenCL.EnqueueUnmapMemObject(CommandQueueID, + memobj.MemID, + mapped_ptr.ToPointer(), + (uint)num_events_in_wait_list, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueUnmapMemObject failed with error code " + result, result); + } + + public void EnqueueUnmapMemObject(Mem memobj, IntPtr mapped_ptr) + { + ErrorCode result; + + result = OpenCL.EnqueueUnmapMemObject(CommandQueueID, + memobj.MemID, + mapped_ptr.ToPointer(), + (uint)0, + null, + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueUnmapMemObject failed with error code " + result, result); + } + + #endregion + + #region EnqueueNDRangeKernel + + /// + /// Execute a parallel kernel. + /// + /// + /// The number of dimensions in the workspace(0-2), must correspond to the number of dimensions in the following arrays + /// null in OpenCL 1.0, but will allow indices to start at non-0 locations + /// Index n of this array=the length of the n'th dimension of global work space + /// Index n of this array=the length of the n'th dimension of local work space + /// + /// + /// + public void EnqueueNDRangeKernel(Kernel kernel, uint workDim, IntPtr[] globalWorkOffset, IntPtr[] globalWorkSize, IntPtr[] localWorkSize, uint numEventsInWaitList, Event[] event_wait_list, out Event _event) + { + ErrorCode result; + IntPtr tmpEvent; + + result = OpenCL.EnqueueNDRangeKernel(CommandQueueID, + kernel.KernelID, + workDim, + globalWorkOffset, + globalWorkSize, + localWorkSize, + numEventsInWaitList, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent); + _event = new Event(Context, tmpEvent); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueNDRangeKernel failed with error code " + result, result); + } + + public void EnqueueNDRangeKernel(Kernel kernel, uint workDim, IntPtr[] globalWorkOffset, IntPtr[] globalWorkSize, IntPtr[] localWorkSize, uint numEventsInWaitList, Event[] event_wait_list) + { + ErrorCode result; + + result = OpenCL.EnqueueNDRangeKernel(CommandQueueID, + kernel.KernelID, + workDim, + globalWorkOffset, + globalWorkSize, + localWorkSize, + numEventsInWaitList, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueNDRangeKernel failed with error code " + result, result); + } + + public void EnqueueNDRangeKernel(Kernel kernel, uint workDim, IntPtr[] globalWorkOffset, IntPtr[] globalWorkSize, IntPtr[] localWorkSize) + { + ErrorCode result; + + result = OpenCL.EnqueueNDRangeKernel(CommandQueueID, + kernel.KernelID, + workDim, + globalWorkOffset, + globalWorkSize, + localWorkSize, + 0, + null, + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueNDRangeKernel failed with error code " + result, result); + } + + #endregion + + #region EnqueueTask + + /// + /// Execute a simple kernel + /// + /// + /// + /// + /// + public void EnqueueTask(Kernel kernel, int numEventsInWaitList, Event[] event_wait_list, out Event _event) + { + ErrorCode result; + IntPtr tmpEvent; + + result = (ErrorCode)OpenCL.EnqueueTask(CommandQueueID, + kernel.KernelID, + (uint)numEventsInWaitList, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent); + _event = new Event(Context, tmpEvent); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueTask failed with error code " + result, result); + } + + /// + /// Execute a simple kernel + /// + /// + /// + /// + public void EnqueueTask(Kernel kernel, int numEventsInWaitList, Event[] event_wait_list) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.EnqueueTask(CommandQueueID, + kernel.KernelID, + (uint)numEventsInWaitList, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueTask failed with error code " + result, result); + } + + /// + /// Execute a simple kernel + /// + /// + public void EnqueueTask(Kernel kernel) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.EnqueueTask(CommandQueueID, + kernel.KernelID, + (uint)0, + null, + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueTask failed with error code " + result, result); + } + + #endregion + + #region EnqueueNativeKernel + + /// + /// Enquque a user function. This function is only supported if + /// DeviceExecCapabilities.NATIVE_KERNEL set in Device.ExecutionCapabilities + /// + /// NOTE: As the delegate is being passed to an unmanaged function, + /// it is the caller's responsibility to maintain a reference to the + /// delegate so it does not get garbage collected before the callback happens. + /// Failure to do this will cause crashes. + /// + /// + /// + /// + /// + public void EnqueueNativeKernel(NativeKernel nativeKernel, int numEventsInWaitList, Event[] event_wait_list, out Event _event) + { + ErrorCode result; + IntPtr tmpEvent; + + result = OpenCL.EnqueueNativeKernel(CommandQueueID, + nativeKernel, + null, + IntPtr.Zero, + 0, + null, + null, + (uint)numEventsInWaitList, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueNativeKernel failed with error code " + result, result); + _event = new Event(Context, tmpEvent); + } + + /// + /// Enquque a user function. This function is only supported if + /// DeviceExecCapabilities.NATIVE_KERNEL set in Device.ExecutionCapabilities + /// + /// NOTE: As the delegate is being passed to an unmanaged function, + /// it is the caller's responsibility to maintain a reference to the + /// delegate so it does not get garbage collected before the callback happens. + /// Failure to do this will cause crashes. + /// + /// + /// + /// + public void EnqueueNativeKernel(NativeKernel nativeKernel, int numEventsInWaitList, Event[] event_wait_list) + { + ErrorCode result; + + result = OpenCL.EnqueueNativeKernel(CommandQueueID, + nativeKernel, + null, + IntPtr.Zero, + 0, + null, + null, + (uint)numEventsInWaitList, + InteropTools.ConvertEventsToEventIDs( event_wait_list ), + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueNativeKernel failed with error code " + result, result); + } + + /// + /// Enquque a user function. This function is only supported if + /// DeviceExecCapabilities.NATIVE_KERNEL set in Device.ExecutionCapabilities + /// + /// NOTE: As the delegate is being passed to an unmanaged function, + /// it is the caller's responsibility to maintain a reference to the + /// delegate so it does not get garbage collected before the callback happens. + /// Failure to do this will cause crashes. + /// + /// + public void EnqueueNativeKernel(NativeKernel nativeKernel) + { + ErrorCode result; + + result = OpenCL.EnqueueNativeKernel(CommandQueueID, + nativeKernel, + null, + IntPtr.Zero, + 0, + null, + null, + 0, + null, + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueNativeKernel failed with error code " + result, result); + } + + #endregion + + #region EnqueueAcquireGLObjects + + public void EnqueueAcquireGLObjects(int numObjects, Mem[] memObjects, int numEventsInWaitList, Event[] event_wait_list, out Event _event) + { + IntPtr tmpEvent; + ErrorCode result; + + result = OpenCL.EnqueueAcquireGLObjects(CommandQueueID, + (uint)numObjects, + InteropTools.ConvertMemToMemIDs(memObjects), + (uint)numEventsInWaitList, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueAcquireGLObjects failed with error code " + result, result); + _event = new Event(Context, tmpEvent); + } + + public void EnqueueAcquireGLObjects(int numObjects, Mem[] memObjects, int numEventsInWaitList, Event[] event_wait_list) + { + ErrorCode result; + + result = OpenCL.EnqueueAcquireGLObjects(CommandQueueID, + (uint)numObjects, + InteropTools.ConvertMemToMemIDs(memObjects), + (uint)numEventsInWaitList, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueAcquireGLObjects failed with error code " + result, result); + } + + public void EnqueueAcquireGLObjects(int numObjects, Mem[] memObjects) + { + ErrorCode result; + + result = OpenCL.EnqueueAcquireGLObjects(CommandQueueID, + (uint)numObjects, + InteropTools.ConvertMemToMemIDs(memObjects), + (uint)0, + null, + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueAcquireGLObjects failed with error code " + result, result); + } + + #endregion + + #region EnqueueReleaseGLObjects + + public void EnqueueReleaseGLObjects(int numObjects, Mem[] memObjects, int numEventsInWaitList, Event[] event_wait_list, out Event _event) + { + IntPtr tmpEvent; + ErrorCode result; + + result = OpenCL.EnqueueReleaseGLObjects(CommandQueueID, + (uint)numObjects, + InteropTools.ConvertMemToMemIDs(memObjects), + (uint)numEventsInWaitList, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + &tmpEvent); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueReleaseGLObjects failed with error code " + result, result); + _event = new Event(Context, tmpEvent); + } + + public void EnqueueReleaseGLObjects(int numObjects, Mem[] memObjects, int numEventsInWaitList, Event[] event_wait_list) + { + ErrorCode result; + + result = OpenCL.EnqueueReleaseGLObjects(CommandQueueID, + (uint)numObjects, + InteropTools.ConvertMemToMemIDs(memObjects), + (uint)numEventsInWaitList, + InteropTools.ConvertEventsToEventIDs(event_wait_list), + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueReleaseGLObjects failed with error code " + result, result); + } + + public void EnqueueReleaseGLObjects(int numObjects, Mem[] memObjects) + { + ErrorCode result; + + result = OpenCL.EnqueueReleaseGLObjects(CommandQueueID, + (uint)numObjects, + InteropTools.ConvertMemToMemIDs(memObjects), + (uint)0, + null, + null); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("EnqueueReleaseGLObjects failed with error code " + result, result); + } + + #endregion + + #region EnqueueMarker + + public void EnqueueMarker( out Event _event ) + { + IntPtr tmpEvent; + + OpenCL.EnqueueMarker(CommandQueueID, &tmpEvent); + _event = new Event(Context, tmpEvent); + } + + #endregion + + #region EnqueueWaitForEvents + + public void EnqueueWaitForEvents( int num_events, Event[] _event_list ) + { + OpenCL.EnqueueWaitForEvents( CommandQueueID, (uint)num_events, InteropTools.ConvertEventsToEventIDs(_event_list) ); + } + + #endregion + + #region EnqueueBarrier + + public void EnqueueBarrier() + { + OpenCL.EnqueueBarrier(CommandQueueID); + } + + #endregion + + #region Flush + + public void Flush() + { + OpenCL.Flush(CommandQueueID); + } + + #endregion + + #region Finish + + public void Finish() + { + OpenCL.Finish(CommandQueueID); + } + + #endregion + + public void SetProperty(CommandQueueProperties properties, bool enable, out CommandQueueProperties oldProperties) + { + ErrorCode result; + ulong returnedProperties = 0; + + result = (ErrorCode)OpenCL.SetCommandQueueProperty( CommandQueueID, + (ulong)properties, + enable, + out returnedProperties ); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "SetCommandQueueProperty failed with error code "+result , result); + oldProperties = (CommandQueueProperties)returnedProperties; + } + + public static implicit operator IntPtr( CommandQueue cq ) + { + return cq.CommandQueueID; + } + } +} diff --git a/OpenCLNet/Context.cs b/OpenCLNet/Context.cs new file mode 100644 index 0000000..781eead --- /dev/null +++ b/OpenCLNet/Context.cs @@ -0,0 +1,517 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Text; +using System.IO; + +namespace OpenCLNet +{ + + unsafe public class Context : IDisposable, InteropTools.IPropertyContainer + { + public IntPtr ContextID { get; protected set; } + public Platform Platform { get; protected set; } + + /// + /// True if there is at least one 64 bit device in the context. + /// This guarantees that variables such as intptr_t, size_t etc are 64 bit + /// + public bool Is64BitContext { get; protected set; } + + // Track whether Dispose has been called. + private bool disposed = false; + + #region Construction / Destruction + + internal Context( Platform platform, IntPtr contextID ) + { + Platform = platform; + ContextID = contextID; + Is64BitContext = ContainsA64BitDevice(); + } + + internal Context( Platform platform, ContextProperties[] properties, Device[] devices ) + { + IntPtr[] intPtrProperties; + IntPtr[] deviceIDs; + ErrorCode result; + + Platform = platform; + deviceIDs = InteropTools.ConvertDevicesToDeviceIDs( devices ); + + intPtrProperties = new IntPtr[properties.Length]; + for( int i=0; i + /// Query which ImageFormats are supported by this context + /// + /// + /// + /// + public ImageFormat[] GetSupportedImageFormats(MemFlags flags, MemObjectType type) + { + uint numImageFormats; + ImageFormat[] imageFormats; + ErrorCode result; + + result = OpenCL.GetSupportedImageFormats(ContextID, (ulong)flags, (uint)type, (uint)0, null, out numImageFormats); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException("GetSupportedImageFormats failed with error code " + result, result); + + imageFormats = new ImageFormat[numImageFormats]; + + result = OpenCL.GetSupportedImageFormats(ContextID, (ulong)flags, (uint)type, numImageFormats, imageFormats, out numImageFormats); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("GetSupportedImageFormats failed with error code " + result, result); + + return imageFormats; + } + + /// + /// Convenience function. Checks if a context supports a specific image format + /// + /// + /// + /// + /// + /// true if the image format is supported, false otherwise + public bool SupportsImageFormat(MemFlags flags, MemObjectType type, ChannelOrder channelOrder, ChannelType channelType) + { + ImageFormat[] imageFormats = GetSupportedImageFormats(flags, type); + foreach (ImageFormat imageFormat in imageFormats) + { + if (imageFormat.ChannelOrder == channelOrder && imageFormat.ChannelType == channelType) + return true; + } + return false; + } + + #endregion + + #region WaitForEvents + + /// + /// Block until the event fires + /// + /// + public void WaitForEvent(Event _event) + { + Event[] event_list = new Event[1]; + + event_list[0] = _event; + OpenCL.WaitForEvents(1, InteropTools.ConvertEventsToEventIDs(event_list)); + } + + /// + /// Block until all events in the array have fired + /// + /// + /// + public void WaitForEvents(int num_events, Event[] event_list) + { + OpenCL.WaitForEvents((uint)num_events, InteropTools.ConvertEventsToEventIDs(event_list)); + } + + #endregion + + #region HasExtension + + public bool HasExtension(string extension) + { + foreach (Device d in Devices) + if (!d.HasExtension(extension)) + return false; + return true; + } + + public bool HasExtensions(string[] extensions) + { + foreach (Device d in Devices) + if (!d.HasExtensions(extensions)) + return false; + return true; + } + + #endregion + + public static implicit operator IntPtr( Context c ) + { + return c.ContextID; + } + + #region IPropertyContainer Members + + unsafe public IntPtr GetPropertySize( uint key ) + { + IntPtr size; + ErrorCode result; + + result = (ErrorCode)OpenCL.GetContextInfo( ContextID, key, IntPtr.Zero, null, out size ); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "GetContextInfo failed: "+result, result); + return size; + } + + unsafe public void ReadProperty( uint key, IntPtr keyLength, void* pBuffer ) + { + IntPtr size; + ErrorCode result; + + result = (ErrorCode)OpenCL.GetContextInfo( ContextID, key, keyLength, pBuffer, out size ); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "GetContextInfo failed: "+result, result); + } + + #endregion + } +} diff --git a/OpenCLNet/Device.cs b/OpenCLNet/Device.cs new file mode 100644 index 0000000..d7db680 --- /dev/null +++ b/OpenCLNet/Device.cs @@ -0,0 +1,398 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Text; + +namespace OpenCLNet +{ + unsafe public class Device : InteropTools.IPropertyContainer + { + protected HashSet ExtensionHashSet = new HashSet(); + + internal Device(Platform platform, IntPtr deviceID) + { + Platform = platform; + DeviceID = deviceID; + + InitializeExtensionHashSet(); + } + + // User-defined conversion from double to Digit + public static implicit operator IntPtr( Device d ) + { + return d.DeviceID; + } + + #region Properties + + public IntPtr DeviceID { get; protected set; } + + public DeviceType DeviceType { get { return (DeviceType) InteropTools.ReadULong( this, (uint)DeviceInfo.TYPE ); } } + public uint VendorID { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.VENDOR_ID ); } } + /// + /// The number of parallel compute cores on the OpenCL device. The minimum value is 1. + /// + public uint MaxComputeUnits { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.MAX_COMPUTE_UNITS ); } } + /// + /// Maximum dimensions that specify the global and local work-item IDs used by the data parallel execution model. + /// (Refer to clEnqueueNDRangeKernel). The minimum value is 3. + /// + public uint MaxWorkItemDimensions { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.MAX_WORK_ITEM_DIMENSIONS ); } } + /// + /// Maximum number of work-items that can be specified in each dimension of + /// the work-group to clEnqueueNDRangeKernel. + /// + /// Returns n size_t entries, where n is the value returned by the query for + /// CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS. + /// + /// The minimum value is (1, 1, 1). + /// + public IntPtr[] MaxWorkItemSizes { get { return InteropTools.ReadIntPtrArray( this, (uint)DeviceInfo.MAX_WORK_ITEM_SIZES ); } } + /// + /// Maximum number of work-items in a work-group executing a kernel using the data parallel execution model. + /// (Refer to clEnqueueNDRangeKernel). + /// + /// The minimum value is 1. + /// + public long MaxWorkGroupSize { get { return InteropTools.ReadIntPtr( this, (uint)DeviceInfo.MAX_WORK_GROUP_SIZE ).ToInt64(); } } + public uint PreferredVectorWidthChar { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.PREFERRED_VECTOR_WIDTH_CHAR ); } } + public uint PreferredVectorWidthShort { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.PREFERRED_VECTOR_WIDTH_SHORT ); } } + public uint PreferredVectorWidthInt { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.PREFERRED_VECTOR_WIDTH_INT ); } } + public uint PreferredVectorWidthLong { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.PREFERRED_VECTOR_WIDTH_LONG ); } } + public uint PreferredVectorWidthFloat { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.PREFERRED_VECTOR_WIDTH_FLOAT ); } } + public uint PreferredVectorWidthDouble { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.PREFERRED_VECTOR_WIDTH_DOUBLE ); } } + /// + /// Maximum configured clock frequency of the device in MHz. + /// + public uint MaxClockFrequency { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.MAX_CLOCK_FREQUENCY ); } } + /// + /// The default compute device address space size specified as an unsigned + /// integer value in bits. Currently supported values are 32 or 64 bits. + /// + public uint AddressBits { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.ADDRESS_BITS ); } } + /// + /// Max size of memory object allocation in bytes. The minimum value is max + /// (1/4th of CL_DEVICE_GLOBAL_MEM_SIZE, 128*1024*1024) + /// + public ulong MaxMemAllocSize { get { return InteropTools.ReadULong( this, (uint)DeviceInfo.MAX_MEM_ALLOC_SIZE ); } } + /// + /// Is true if images are supported by the OpenCL device and CL_FALSE otherwise. + /// + public bool ImageSupport { get { return InteropTools.ReadBool( this, (uint)DeviceInfo.IMAGE_SUPPORT ); } } + /// + /// Max number of simultaneous image objects that can be read by a kernel. + /// The minimum value is 128 if CL_DEVICE_IMAGE_SUPPORT is true. + /// + public uint MaxReadImageArgs { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.MAX_READ_IMAGE_ARGS ); } } + /// + /// Max number of simultaneous image objects that can be written to by a + /// kernel. The minimum value is 8 if CL_DEVICE_IMAGE_SUPPORT is true. + /// + public uint MaxWriteImageArgs { get { return InteropTools.ReadUInt(this, (uint)DeviceInfo.MAX_WRITE_IMAGE_ARGS); } } + /// + /// Max width of 2D image in pixels. The minimum value is 8192 if CL_DEVICE_IMAGE_SUPPORT is true. + /// + public long Image2DMaxWidth { get { return InteropTools.ReadIntPtr( this, (uint)DeviceInfo.IMAGE2D_MAX_WIDTH ).ToInt64(); } } + /// + /// Max height of 2D image in pixels. The minimum value is 8192 if CL_DEVICE_IMAGE_SUPPORT is true. + /// + public long Image2DMaxHeight { get { return InteropTools.ReadIntPtr( this, (uint)DeviceInfo.IMAGE2D_MAX_HEIGHT ).ToInt64(); } } + /// + /// Max width of 3D image in pixels. The minimum value is 2048 if CL_DEVICE_IMAGE_SUPPORT is true. + /// + public long Image3DMaxWidth { get { return InteropTools.ReadIntPtr( this, (uint)DeviceInfo.IMAGE3D_MAX_WIDTH ).ToInt64(); } } + /// + /// Max height of 3D image in pixels. The minimum value is 2048 if CL_DEVICE_IMAGE_SUPPORT is true. + /// + public long Image3DMaxHeight { get { return InteropTools.ReadIntPtr( this, (uint)DeviceInfo.IMAGE3D_MAX_HEIGHT ).ToInt64(); } } + /// + /// Max depth of 3D image in pixels. The minimum value is 2048 if CL_DEVICE_IMAGE_SUPPORT is true. + /// + public long Image3DMaxDepth { get { return InteropTools.ReadIntPtr( this, (uint)DeviceInfo.IMAGE3D_MAX_DEPTH ).ToInt64(); } } + /// + /// Maximum number of samplers that can be used in a kernel. Refer to section 6.11.8 for a detailed + /// description on samplers. The minimum value is 16 if CL_DEVICE_IMAGE_SUPPORT is true. + /// + public uint MaxSamplers { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.MAX_SAMPLERS ); } } + /// + /// Max size in bytes of the arguments that can be passed to a kernel. The minimum value is 256. + /// + public long MaxParameterSize { get { return InteropTools.ReadIntPtr( this, (uint)DeviceInfo.MAX_PARAMETER_SIZE ).ToInt64(); } } + /// + /// Describes the alignment in bits of the base address of any allocated memory object. + /// + public uint MemBaseAddrAlign { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.MEM_BASE_ADDR_ALIGN ); } } + /// + /// The smallest alignment in bytes which can be used for any data type. + /// + public uint MinDataTypeAlignSize { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.MIN_DATA_TYPE_ALIGN_SIZE ); } } + public ulong SingleFPConfig { get { return InteropTools.ReadULong( this, (uint)DeviceInfo.SINGLE_FP_CONFIG ); } } + /// + /// Type of global memory cache supported. Valid values are: CL_NONE, CL_READ_ONLY_CACHE and CL_READ_WRITE_CACHE. + /// + public DeviceMemCacheType GlobalMemCacheType { get { return (DeviceMemCacheType)InteropTools.ReadUInt( this, (uint)DeviceInfo.GLOBAL_MEM_CACHE_TYPE ); } } + /// + /// Size of global memory cache line in bytes. + /// + public uint GlobalMemCacheLineSize { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.GLOBAL_MEM_CACHELINE_SIZE ); } } + /// + /// Size of global memory cache in bytes. + /// + public ulong GlobalMemCacheSize { get { return InteropTools.ReadULong( this, (uint)DeviceInfo.GLOBAL_MEM_CACHE_SIZE ); } } + /// + /// Size of global device memory in bytes. + /// + public ulong GlobalMemSize { get { return InteropTools.ReadULong( this, (uint)DeviceInfo.GLOBAL_MEM_SIZE ); } } + /// + /// Max size in bytes of a constant buffer allocation. The minimum value is 64 KB. + /// + public ulong MaxConstantBufferSize { get { return InteropTools.ReadULong( this, (uint)DeviceInfo.MAX_CONSTANT_BUFFER_SIZE ); } } + /// + /// Max number of arguments declared with the __constant qualifier in a kernel. The minimum value is 8. + /// + public uint MaxConstantArgs { get { return InteropTools.ReadUInt( this, (uint)DeviceInfo.MAX_CONSTANT_ARGS ); } } + /// + /// Type of local memory supported. This can be set to CL_LOCAL implying dedicated local memory storage such as SRAM, or CL_GLOBAL. + /// + public DeviceLocalMemType LocalMemType { get { return (DeviceLocalMemType)InteropTools.ReadUInt( this, (uint)DeviceInfo.LOCAL_MEM_TYPE ); } } + /// + /// Size of local memory arena in bytes. The minimum value is 16 KB. + /// + public ulong LocalMemSize { get { return InteropTools.ReadULong( this, (uint)DeviceInfo.LOCAL_MEM_SIZE ); } } + /// + /// Is CL_TRUE if the device implements error correction for the memories, + /// caches, registers etc. in the device. Is CL_FALSE if the device does not + /// implement error correction. This can be a requirement for certain clients of OpenCL. + /// + public bool ErrorCorrectionSupport { get { return InteropTools.ReadBool( this, (uint)DeviceInfo.ERROR_CORRECTION_SUPPORT ); } } + /// + /// Describes the resolution of device timer. This is measured in nanoseconds. Refer to section 5.9 for details. + /// + public ulong ProfilingTimerResolution { get { return (ulong)InteropTools.ReadIntPtr( this, (uint)DeviceInfo.PROFILING_TIMER_RESOLUTION ).ToInt64(); } } + /// + /// Is CL_TRUE if the OpenCL device is a little endian device and CL_FALSE otherwise. + /// + public bool EndianLittle { get { return InteropTools.ReadBool( this, (uint)DeviceInfo.ENDIAN_LITTLE ); } } + /// + /// Is CL_TRUE if the device is available and CL_FALSE if the device is not available. + /// + public bool Available { get { return InteropTools.ReadBool( this, (uint)DeviceInfo.AVAILABLE ); } } + /// + /// Is CL_FALSE if the implementation does not have a compiler available to compile the program source. + /// Is CL_TRUE if the compiler is available. + /// This can be CL_FALSE for the embededed platform profile only. + /// + public bool CompilerAvailable { get { return InteropTools.ReadBool( this, (uint)DeviceInfo.COMPILER_AVAILABLE ); } } + /// + /// Describes the execution capabilities of the device. This is a bit-field that describes one or more of the following values: + /// CL_EXEC_KERNEL – The OpenCL device can execute OpenCL kernels. + /// CL_EXEC_NATIVE_KERNEL – The OpenCL device can execute native kernels. + /// The mandated minimum capability is: CL_EXEC_KERNEL. + /// + public ulong ExecutionCapabilities { get { return InteropTools.ReadULong( this, (uint)DeviceInfo.EXECUTION_CAPABILITIES ); } } + /// + /// Describes the command-queue properties supported by the device. + /// This is a bit-field that describes one or more of the following values: + /// CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE + /// CL_QUEUE_PROFILING_ENABLE + /// These properties are described in table 5.1. + /// + /// The mandated minimum capability is: + /// CL_QUEUE_PROFILING_ENABLE. + /// + public ulong QueueProperties { get { return InteropTools.ReadULong( this, (uint)DeviceInfo.QUEUE_PROPERTIES ); } } + /// + /// The platform associated with this device. + /// + public Platform Platform { get; protected set; } + /// + /// Device name string. + /// + public string Name { get { return InteropTools.ReadString( this, (uint)DeviceInfo.NAME ); } } + /// + /// Vendor name string. + /// + public string Vendor { get { return InteropTools.ReadString( this, (uint)DeviceInfo.VENDOR ); } } + /// + /// OpenCL software driver version string in the form major_number.minor_number. + /// + public string DriverVersion { get { return InteropTools.ReadString( this, (uint)DeviceInfo.DRIVER_VERSION ); } } + /// + /// OpenCL profile string. Returns the profile name supported by the device. + /// The profile name returned can be one of the following strings: + /// FULL_PROFILE – if the device supports the OpenCL specification (functionality defined as part of the + /// core specification and does not require any extensions to be supported). + /// EMBEDDED_PROFILE - if the device supports the OpenCL embedded profile. + /// + public string Profile { get { return InteropTools.ReadString( this, (uint)DeviceInfo.PROFILE ); } } + /// + /// OpenCL version string. Returns the OpenCL version supported by the device. This version string has the + /// following format: + /// OpenCL + /// The major_version.minor_version value returned will be 1.0. + /// + public string Version { get { return InteropTools.ReadString( this, (uint)DeviceInfo.VERSION ); } } + /// + /// Returns a space separated list of extension names (the extension names themselves do not contain any spaces). + /// The list of extension names returned currently can include one or more of + /// the following approved extension names: + /// cl_khr_fp64 + /// cl_khr_select_fprounding_mode + /// cl_khr_global_int32_base_atomics + /// cl_khr_global_int32_extended_atomics + /// cl_khr_local_int32_base_atomics + /// cl_khr_local_int32_extended_atomics + /// cl_khr_int64_base_atomics + /// cl_khr_int64_extended_atomics + /// cl_khr_3d_image_writes + /// cl_khr_byte_addressable_store + /// cl_khr_fp16 + /// cl_khr_gl_sharing + /// Please refer to section 9 for a detailed + /// description of these extensions. + /// + public string Extensions { get { return InteropTools.ReadString( this, (uint)DeviceInfo.EXTENSIONS ); } } + + #endregion + + #region IPropertyContainer Members + + public IntPtr GetPropertySize( uint key ) + { + IntPtr size; + ErrorCode result; + + result = (ErrorCode)OpenCL.GetDeviceInfo( DeviceID, key, IntPtr.Zero, null, out size ); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "Unable to get device info for device "+DeviceID, result); + return size; + } + + public void ReadProperty( uint key, IntPtr keyLength, void* pBuffer ) + { + IntPtr size; + ErrorCode result; + + result = (ErrorCode)OpenCL.GetDeviceInfo( DeviceID, (uint)key, keyLength, pBuffer, out size ); + if( result!=(int)ErrorCode.SUCCESS ) + throw new OpenCLException( "Unable to get device info for device "+DeviceID, result); + } + + #endregion + + #region HasExtension + + protected void InitializeExtensionHashSet() + { + string[] ext = Extensions.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + + foreach (string s in ext) + ExtensionHashSet.Add(s); + } + + public bool HasExtension(string extension) + { + return ExtensionHashSet.Contains(extension); + } + + public bool HasExtensions(string[] extensions) + { + foreach (string s in extensions) + if (!ExtensionHashSet.Contains(s)) + return false; + return true; + } + + #endregion + + #region ToString + + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + + sb.AppendLine( "Name: "+Name ); + sb.AppendLine( "Vendor: "+Vendor ); + sb.AppendLine( "VendorID: "+VendorID ); + sb.AppendLine( "DriverVersion: "+DriverVersion ); + sb.AppendLine( "Profile: "+Profile ); + sb.AppendLine( "Version: "+Version ); + sb.AppendLine( "Extensions: "+Extensions ); + sb.AppendLine( "DeviceType: "+DeviceType ); + sb.AppendLine( "MaxComputeUnits: "+MaxComputeUnits ); + sb.AppendLine( "MaxWorkItemDimensions: "+MaxWorkItemDimensions ); + sb.Append( "MaxWorkItemSizes:" ); + for( int i=0; i BuildLogs = new List(); + + public OpenCLBuildException( Program program, ErrorCode result ) + : base( "Build failed with error code "+result, result ) + { + foreach (Device d in program.Devices) + { + BuildLogs.Add( program.GetBuildLog(d) ); + } + } + } +} diff --git a/OpenCLNet/Image.cs b/OpenCLNet/Image.cs new file mode 100644 index 0000000..45919e7 --- /dev/null +++ b/OpenCLNet/Image.cs @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Runtime.InteropServices; + +namespace OpenCLNet +{ + public unsafe class Image : Mem + { + internal Image(Context context, IntPtr memID) + : base(context,memID) + { + } + + #region Properties + + public ImageFormat ImageFormat + { + get + { + IntPtr size = GetPropertySize((uint)ImageInfo.FORMAT); + byte* pBuffer = stackalloc byte[(int)size]; + + ReadProperty((uint)ImageInfo.FORMAT, size, pBuffer); + return (ImageFormat)Marshal.PtrToStructure((IntPtr)pBuffer, typeof(ImageFormat)); + } + } + public IntPtr ElementSize { get { return InteropTools.ReadIntPtr(this, (uint)ImageInfo.ELEMENT_SIZE); } } + public IntPtr RowPitch { get { return InteropTools.ReadIntPtr(this, (uint)ImageInfo.ROW_PITCH); } } + public IntPtr SlicePitch { get { return InteropTools.ReadIntPtr(this, (uint)ImageInfo.SLICE_PITCH); } } + public IntPtr Width { get { return InteropTools.ReadIntPtr(this, (uint)ImageInfo.WIDTH); } } + public IntPtr Height { get { return InteropTools.ReadIntPtr(this, (uint)ImageInfo.HEIGHT); } } + public IntPtr Depth { get { return InteropTools.ReadIntPtr(this, (uint)ImageInfo.DEPTH); } } + + #endregion + + // Override the IPropertyContainer interface of the Mem class. + #region IPropertyContainer Members + + public override unsafe IntPtr GetPropertySize(uint key) + { + IntPtr size; + ErrorCode result; + + result = (ErrorCode)OpenCL.GetImageInfo(MemID, key, IntPtr.Zero, null, out size); + if (result != ErrorCode.SUCCESS) + { + size = base.GetPropertySize(key); + } + return size; + } + + public override unsafe void ReadProperty(uint key, IntPtr keyLength, void* pBuffer) + { + IntPtr size; + ErrorCode result; + + result = (ErrorCode)OpenCL.GetImageInfo(MemID, key, keyLength, pBuffer, out size); + if (result != ErrorCode.SUCCESS) + { + base.ReadProperty(key, keyLength, pBuffer); + } + } + + #endregion + } +} diff --git a/OpenCLNet/InteropTools.cs b/OpenCLNet/InteropTools.cs new file mode 100644 index 0000000..586a8f3 --- /dev/null +++ b/OpenCLNet/InteropTools.cs @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Text; + +namespace OpenCLNet +{ + public class InteropTools + { + public unsafe interface IPropertyContainer + { + IntPtr GetPropertySize(uint key); + void ReadProperty(uint key, IntPtr keyLength, void* pBuffer); + } + + public static byte[] CreateNullTerminatedString(string s) + { + int len; + byte[] data; + + len = Encoding.UTF8.GetByteCount(s); + data = new byte[len + 1]; + Encoding.UTF8.GetBytes(s, 0, s.Length, data, 0); + data[len] = 0; + return data; + } + + public static IntPtr[] ConvertDevicesToDeviceIDs(Device[] devices) + { + IntPtr[] deviceIDs; + + if (devices == null) + return null; + + deviceIDs = new IntPtr[devices.Length]; + for (int i = 0; i < devices.Length; i++) + deviceIDs[i] = devices[i]; + return deviceIDs; + } + + public static Device[] ConvertDeviceIDsToDevices(Platform platform, IntPtr[] deviceIDs) + { + Device[] devices; + + if (deviceIDs == null) + return null; + + devices = new Device[deviceIDs.Length]; + for (int i = 0; i < deviceIDs.Length; i++) + devices[i] = platform.GetDevice(deviceIDs[i]); + return devices; + } + + public static IntPtr[] ConvertMemToMemIDs(Mem[] mems) + { + IntPtr[] memIDs; + + if (mems == null) + return null; + + memIDs = new IntPtr[mems.Length]; + for (int i = 0; i < mems.Length; i++) + memIDs[i] = mems[i].MemID; + return memIDs; + } + + public static IntPtr[] ConvertEventsToEventIDs(Event[] events) + { + IntPtr[] eventIDs; + + if (events == null) + return null; + + eventIDs = new IntPtr[events.Length]; + for (int i = 0; i < events.Length; i++) + eventIDs[i] = events[i]; + return eventIDs; + } + + #region Helper functions to read properties + + unsafe public static bool ReadBool(IPropertyContainer propertyContainer, uint key) + { + return ReadUInt(propertyContainer, key) == (uint)Bool.TRUE ? true : false; + } + + unsafe public static byte[] ReadBytes(IPropertyContainer propertyContainer, uint key) + { + IntPtr size; + + size = propertyContainer.GetPropertySize(key); + byte[] data = new byte[size.ToInt64()]; + fixed (byte* pData = data) + { + propertyContainer.ReadProperty(key, size, pData); + } + return data; + } + + unsafe public static string ReadString(IPropertyContainer propertyContainer, uint key) + { + IntPtr size; + string s; + + size = propertyContainer.GetPropertySize((uint)key); + byte[] stringData = new byte[size.ToInt64()]; + fixed (byte* pStringData = stringData) + { + propertyContainer.ReadProperty((uint)key, size, pStringData); + } + + s = Encoding.UTF8.GetString(stringData); + int nullIndex = s.IndexOf('\0'); + if (nullIndex >= 0) + return s.Substring(0, nullIndex); + else + return s; + } + + unsafe public static int ReadInt(IPropertyContainer propertyContainer, uint key) + { + int output; + + propertyContainer.ReadProperty(key, new IntPtr(sizeof(int)), &output); + return output; + } + + unsafe public static uint ReadUInt(IPropertyContainer propertyContainer, uint key) + { + uint output; + + propertyContainer.ReadProperty(key, new IntPtr(sizeof(uint)), &output); + return output; + } + + unsafe public static long ReadLong(IPropertyContainer propertyContainer, uint key) + { + long output; + + propertyContainer.ReadProperty(key, new IntPtr(sizeof(long)), &output); + return output; + } + + unsafe public static ulong ReadULong(IPropertyContainer propertyContainer, uint key) + { + ulong output; + + propertyContainer.ReadProperty(key, new IntPtr(sizeof(ulong)), &output); + return output; + } + + unsafe public static IntPtr ReadIntPtr(IPropertyContainer propertyContainer, uint key) + { + IntPtr output; + + propertyContainer.ReadProperty(key, new IntPtr(sizeof(IntPtr)), &output); + return output; + } + + unsafe public static IntPtr[] ReadIntPtrArray(IPropertyContainer propertyContainer, uint key) + { + IntPtr size = propertyContainer.GetPropertySize(key); + long numElements = (long)size / sizeof(IntPtr); + IntPtr[] ptrs = new IntPtr[numElements]; + byte[] data = InteropTools.ReadBytes(propertyContainer, key); + + fixed (byte* pData = data) + { + void** pBS = (void**)pData; + for (int i = 0; i < numElements; i++) + ptrs[i] = new IntPtr(pBS[i]); + } + return ptrs; + } + + #endregion + + } +} diff --git a/OpenCLNet/Kernel.cs b/OpenCLNet/Kernel.cs new file mode 100644 index 0000000..7a3dcea --- /dev/null +++ b/OpenCLNet/Kernel.cs @@ -0,0 +1,651 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Text; + +namespace OpenCLNet +{ + /// + /// The Kernel class wraps an OpenCL kernel handle + /// + /// The main purposes of this class is to serve as a handle to + /// a compiled OpenCL function and to set arguments on the function + /// before enqueueing calls. + /// + /// Arguments are set using either the overloaded SetArg functions or + /// explicit Set*Arg functions where * is a type. The most usual types + /// are supported, but no vectors. If you need to set a parameter that's + /// more advanced than what's supported here, use the version of SetArg + /// that takes a pointer and size. + /// + /// Note that pointer arguments are set by passing their OpenCL memory object, + /// not native pointers. + /// + unsafe public class Kernel : InteropTools.IPropertyContainer + { + // Track whether Dispose has been called. + private bool disposed = false; + + public string FunctionName { get { return InteropTools.ReadString( this, (uint)KernelInfo.FUNCTION_NAME ); } } + public uint NumArgs { get { return InteropTools.ReadUInt( this, (uint)KernelInfo.NUM_ARGS ); } } + public uint ReferenceCount { get { return InteropTools.ReadUInt( this, (uint)KernelInfo.REFERENCE_COUNT ); } } + public Context Context { get; protected set; } + public Program Program { get; protected set; } + public IntPtr KernelID { get; set; } + + internal Kernel( Context context, Program program, IntPtr kernelID ) + { + Context = context; + Program = program; + KernelID = kernelID; + } + + ~Kernel() + { + Dispose( false ); + } + + #region IDisposable Members + + // Implement IDisposable. + // Do not make this method virtual. + // A derived class should not be able to override this method. + public void Dispose() + { + Dispose( true ); + // This object will be cleaned up by the Dispose method. + // Therefore, you should call GC.SupressFinalize to + // take this object off the finalization queue + // and prevent finalization code for this object + // from executing a second time. + GC.SuppressFinalize( this ); + } + + // Dispose(bool disposing) executes in two distinct scenarios. + // If disposing equals true, the method has been called directly + // or indirectly by a user's code. Managed and unmanaged resources + // can be disposed. + // If disposing equals false, the method has been called by the + // runtime from inside the finalizer and you should not reference + // other objects. Only unmanaged resources can be disposed. + private void Dispose( bool disposing ) + { + // Check to see if Dispose has already been called. + if( !this.disposed ) + { + // If disposing equals true, dispose all managed + // and unmanaged resources. + if( disposing ) + { + // Dispose managed resources. + } + + // Call the appropriate methods to clean up + // unmanaged resources here. + // If disposing is false, + // only the following code is executed. + OpenCL.ReleaseKernel( KernelID ); + KernelID = IntPtr.Zero; + + // Note disposing has been done. + disposed = true; + } + } + + + #endregion + + public void SetArg( int argIndex, IntPtr argSize, IntPtr argValue ) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg( KernelID, (uint)argIndex, argSize, argValue.ToPointer() ); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "SetArg failed with error code "+result, result); + } + + #region SetArg functions + + /// + /// Set argument argIndex to c + /// + /// + /// + public void SetArg(int argIndex, sbyte c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(sbyte)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + /// + /// Set argument argIndex to c + /// + /// + /// + public void SetArg(int argIndex, byte c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(byte)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + /// + /// Set argument argIndex to c + /// + /// + /// + public void SetArg(int argIndex, short c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(short)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + /// + /// Set argument argIndex to c + /// + /// + /// + public void SetArg(int argIndex, ushort c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(ushort)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + /// + /// Set argument argIndex to c + /// + /// + /// + public void SetArg(int argIndex, int c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(int)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + /// + /// Set argument argIndex to c + /// + /// + /// + public void SetArg(int argIndex, uint c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(uint)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + /// + /// Set argument argIndex to c + /// + /// + /// + public void SetArg(int argIndex, long c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(long)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + /// + /// Set argument argIndex to c + /// + /// + /// + public void SetArg(int argIndex, ulong c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(ulong)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + /// + /// Set argument argIndex to c + /// + /// + /// + public void SetArg( int argIndex, float c ) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(float)), &c); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "SetArg failed with error code "+result, result); + } + + /// + /// Set argument argIndex to c + /// + /// + /// + public void SetArg(int argIndex, double c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(double)), &c); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "SetArg failed with error code "+result, result); + } + + /// + /// Set argument argIndex to c + /// + /// + /// + public void SetArg( int argIndex, IntPtr c ) + { + ErrorCode result; + + if (Context.Is64BitContext) + { + long l = c.ToInt64(); + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(8), &l); + } + else + { + int i = c.ToInt32(); + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(4), &i); + } + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "SetArg failed with error code "+result, result); + } + + /// + /// Set argument argIndex to mem + /// + /// + /// + public void SetArg(int argIndex, Mem mem) + { + ErrorCode result; + IntPtr p = mem.MemID; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(IntPtr)), &p); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + /// + /// Set argument argIndex to sampler + /// + /// + /// + public void SetArg(int argIndex, Sampler sampler) + { + ErrorCode result; + IntPtr p = sampler.SamplerID; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(IntPtr)), &p); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + #endregion + + #region Setargs with explicit function names(For VB mostly) + + public void SetSByteArg(int argIndex, sbyte c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(sbyte)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + public void SetByteArg(int argIndex, byte c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(byte)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + public void SetShortArg(int argIndex, short c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(short)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + public void SetUShortArg(int argIndex, ushort c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(ushort)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + public void SetIntArg(int argIndex, int c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(int)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + public void SetUIntArg(int argIndex, uint c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(uint)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + public void SetLongArg(int argIndex, long c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(long)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + public void SetULongArg(int argIndex, ulong c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(ulong)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + public void SetSingleArg(int argIndex, float c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(float)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + public void SetDoubleArg(int argIndex, double c) + { + ErrorCode result; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(double)), &c); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + public void SetIntPtrArg(int argIndex, IntPtr c) + { + ErrorCode result; + + if (Context.Is64BitContext) + { + long l = c.ToInt64(); + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(8), &l); + } + else + { + int i = c.ToInt32(); + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(4), &i); + } + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + public void SetMemArg(int argIndex, Mem mem) + { + ErrorCode result; + IntPtr p = mem.MemID; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(IntPtr)), &p); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + public void SetSamplerArg(int argIndex, Sampler sampler) + { + ErrorCode result; + IntPtr p = sampler.SamplerID; + + result = (ErrorCode)OpenCL.SetKernelArg(KernelID, (uint)argIndex, new IntPtr(sizeof(IntPtr)), &p); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("SetArg failed with error code " + result, result); + } + + #endregion + +#if false + // Have to add some endian checking before compiling these into the library + + #region Set Char vectors + + public void SetChar2Arg(int argIndex, sbyte s0, sbyte s1) + { + sbyte* pBuffer = stackalloc sbyte[2]; + pBuffer[0] = s0; + pBuffer[1] = s1; + SetArg(argIndex, (IntPtr)(sizeof(sbyte) * 2), (IntPtr)pBuffer); + } + + public void SetChar4Arg(int argIndex, sbyte s0, sbyte s1, sbyte s2, sbyte s3) + { + sbyte* pBuffer = stackalloc sbyte[4]; + pBuffer[0] = s0; + pBuffer[1] = s1; + pBuffer[2] = s2; + pBuffer[3] = s3; + SetArg(argIndex, (IntPtr)(sizeof(sbyte) * 4), (IntPtr)pBuffer); + } + + #endregion + + #region Set UChar vectors + + public void SetUChar2Arg(int argIndex, byte s0, byte s1) + { + byte* pBuffer = stackalloc byte[2]; + pBuffer[0] = s0; + pBuffer[1] = s1; + SetArg(argIndex, (IntPtr)(sizeof(byte) * 2), (IntPtr)pBuffer); + } + + public void SetUChar4Arg(int argIndex, byte s0, byte s1, byte s2, byte s3) + { + byte* pBuffer = stackalloc byte[4]; + pBuffer[0] = s0; + pBuffer[1] = s1; + pBuffer[2] = s2; + pBuffer[3] = s3; + SetArg(argIndex, (IntPtr)(sizeof(byte) * 4), (IntPtr)pBuffer); + } + + #endregion + + #region Set Int vectors + + public void SetInt2Arg(int argIndex, int s0, int s1) + { + int* pBuffer = stackalloc int[2]; + pBuffer[0] = s0; + pBuffer[1] = s1; + SetArg(argIndex, (IntPtr)(sizeof(int) * 2), (IntPtr)pBuffer); + } + + public void SetInt4Arg(int argIndex, int s0, int s1, int s2, int s3) + { + int* pBuffer = stackalloc int[4]; + pBuffer[0] = s0; + pBuffer[1] = s1; + pBuffer[2] = s2; + pBuffer[3] = s3; + SetArg(argIndex, (IntPtr)(sizeof(int) * 4), (IntPtr)pBuffer); + } + + #endregion + + #region Set UInt vectors + + public void SetUInt2Arg(int argIndex, uint s0, uint s1) + { + uint* pBuffer = stackalloc uint[2]; + pBuffer[0] = s0; + pBuffer[1] = s1; + SetArg(argIndex, (IntPtr)(sizeof(uint) * 2), (IntPtr)pBuffer); + } + + public void SetUInt4Arg(int argIndex, uint s0, uint s1, uint s2, uint s3) + { + uint* pBuffer = stackalloc uint[4]; + pBuffer[0] = s0; + pBuffer[1] = s1; + pBuffer[2] = s2; + pBuffer[3] = s3; + SetArg(argIndex, (IntPtr)(sizeof(uint) * 4), (IntPtr)pBuffer); + } + + #endregion + + #region Set Long vectors + + public void SetLong2Arg(int argIndex, long s0, long s1) + { + long* pBuffer = stackalloc long[2]; + pBuffer[0] = s0; + pBuffer[1] = s1; + SetArg(argIndex, (IntPtr)(sizeof(long) * 2), (IntPtr)pBuffer); + } + + public void SetLong4Arg(int argIndex, long s0, long s1, long s2, long s3) + { + long* pBuffer = stackalloc long[4]; + pBuffer[0] = s0; + pBuffer[1] = s1; + pBuffer[2] = s2; + pBuffer[3] = s3; + SetArg(argIndex, (IntPtr)(sizeof(long) * 4), (IntPtr)pBuffer); + } + + #endregion + + #region Set ULong vectors + + public void SetULong2Arg(int argIndex, ulong s0, ulong s1) + { + ulong* pBuffer = stackalloc ulong[2]; + pBuffer[0] = s0; + pBuffer[1] = s1; + SetArg(argIndex, (IntPtr)(sizeof(ulong) * 2), (IntPtr)pBuffer); + } + + public void SetULong4Arg(int argIndex, ulong s0, ulong s1, ulong s2, ulong s3) + { + ulong* pBuffer = stackalloc ulong[4]; + pBuffer[0] = s0; + pBuffer[1] = s1; + pBuffer[2] = s2; + pBuffer[3] = s3; + SetArg(argIndex, (IntPtr)(sizeof(ulong) * 4), (IntPtr)pBuffer); + } + + #endregion + + #region Set Float vectors + + public void SetFloat2Arg(int argIndex, float s0, float s1) + { + float* pBuffer = stackalloc float[2]; + pBuffer[0] = s0; + pBuffer[1] = s1; + SetArg(argIndex, (IntPtr)(sizeof(float) * 2), (IntPtr)pBuffer); + } + + public void SetFloat4Arg(int argIndex, float s0, float s1, float s2, float s3) + { + float* pBuffer = stackalloc float[4]; + pBuffer[0] = s0; + pBuffer[1] = s1; + pBuffer[2] = s2; + pBuffer[3] = s3; + SetArg(argIndex, (IntPtr)(sizeof(float) * 4), (IntPtr)pBuffer); + } + + #endregion + +#endif + public static implicit operator IntPtr( Kernel k ) + { + return k.KernelID; + } + + #region IPropertyContainer Members + + public IntPtr GetPropertySize( uint key ) + { + IntPtr size; + ErrorCode result; + + result = (ErrorCode)OpenCL.GetKernelInfo( KernelID, key, IntPtr.Zero, null, out size ); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "Unable to get kernel info for kernel "+KernelID, result); + return size; + } + + public void ReadProperty( uint key, IntPtr keyLength, void* pBuffer ) + { + IntPtr size; + ErrorCode result; + + result = (ErrorCode)OpenCL.GetKernelInfo( KernelID, (uint)key, keyLength, pBuffer, out size ); + if( result!=(int)ErrorCode.SUCCESS ) + throw new OpenCLException( "Unable to get kernel info for kernel "+KernelID, result); + } + + #endregion + } +} diff --git a/OpenCLNet/Mem.cs b/OpenCLNet/Mem.cs new file mode 100644 index 0000000..bc9b0d1 --- /dev/null +++ b/OpenCLNet/Mem.cs @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Text; + +namespace OpenCLNet +{ + unsafe public class Mem : IDisposable, InteropTools.IPropertyContainer + { + // Track whether Dispose has been called. + private bool disposed = false; + + private TextureInfo TxInfo; + + public IntPtr MemID { get; protected set; } + public Context Context { get; protected set; } + public MemObjectType MemType { get { return (MemObjectType)InteropTools.ReadUInt( this, (uint)MemInfo.TYPE ); } } + public MemFlags MemFlags { get { return (MemFlags)InteropTools.ReadULong( this, (uint)MemInfo.FLAGS ); } } + public IntPtr MemSize { get { return InteropTools.ReadIntPtr( this, (uint)MemInfo.SIZE ); } } + public IntPtr HostPtr { get { return InteropTools.ReadIntPtr( this, (uint)MemInfo.HOST_PTR ); } } + public uint MapCount { get { return InteropTools.ReadUInt( this, (uint)MemInfo.MAP_COUNT ); } } + public uint ReferenceCount { get { return InteropTools.ReadUInt( this, (uint)MemInfo.REFERENCE_COUNT ); } } + + public uint TextureTarget { get { return InteropTools.ReadUInt(TxInfo, (uint)CLGLTextureInfo.TEXTURE_TARGET); } } + public int MipMapLevel { get { return InteropTools.ReadInt(TxInfo, (uint)CLGLTextureInfo.MIPMAP_LEVEL); } } + + + #region Construction / Destruction + + internal Mem( Context context, IntPtr memID ) + { + Context = context; + MemID = memID; + TxInfo = new TextureInfo(this); + } + + // Use C# destructor syntax for finalization code. + // This destructor will run only if the Dispose method + // does not get called. + // It gives your base class the opportunity to finalize. + // Do not provide destructors in types derived from this class. + ~Mem() + { + // Do not re-create Dispose clean-up code here. + // Calling Dispose(false) is optimal in terms of + // readability and maintainability. + Dispose( false ); + } + + #endregion + + #region IDisposable Members + + // Implement IDisposable. + // Do not make this method virtual. + // A derived class should not be able to override this method. + public void Dispose() + { + Dispose( true ); + // This object will be cleaned up by the Dispose method. + // Therefore, you should call GC.SupressFinalize to + // take this object off the finalization queue + // and prevent finalization code for this object + // from executing a second time. + GC.SuppressFinalize( this ); + } + + // Dispose(bool disposing) executes in two distinct scenarios. + // If disposing equals true, the method has been called directly + // or indirectly by a user's code. Managed and unmanaged resources + // can be disposed. + // If disposing equals false, the method has been called by the + // runtime from inside the finalizer and you should not reference + // other objects. Only unmanaged resources can be disposed. + private void Dispose( bool disposing ) + { + // Check to see if Dispose has already been called. + if( !this.disposed ) + { + // If disposing equals true, dispose all managed + // and unmanaged resources. + if( disposing ) + { + // Dispose managed resources. + } + + // Call the appropriate methods to clean up + // unmanaged resources here. + // If disposing is false, + // only the following code is executed. + OpenCL.ReleaseMemObject( MemID ); + MemID = IntPtr.Zero; + + // Note disposing has been done. + disposed = true; + } + } + + #endregion + + + public void GetGLObjectInfo(out CLGLObjectType glObjectType, out IntPtr glObjectName) + { + ErrorCode result; + uint type; + uint name; + + result = OpenCL.GetGLObjectInfo(MemID, out type, out name); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("GetGLObjectInfo failed: " + result, result); + glObjectType = (CLGLObjectType)type; + glObjectName = (IntPtr)name; + } + + + #region IPropertyContainer Members + + unsafe public virtual IntPtr GetPropertySize( uint key ) + { + IntPtr size; + ErrorCode result; + + result = (ErrorCode)OpenCL.GetMemObjectInfo( MemID, key, IntPtr.Zero, null, out size ); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "GetMemObjectInfo failed: "+result, result ); + return size; + } + + unsafe public virtual void ReadProperty( uint key, IntPtr keyLength, void* pBuffer ) + { + IntPtr size; + ErrorCode result; + + result = (ErrorCode)OpenCL.GetMemObjectInfo( MemID, key, keyLength, pBuffer, out size ); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "GetMemObjectInfo failed: "+result, result ); + } + + #endregion + + + class TextureInfo : InteropTools.IPropertyContainer + { + Mem Mem; + + public TextureInfo(Mem mem) + { + Mem = mem; + } + + #region IPropertyContainer Members + + public IntPtr GetPropertySize(uint key) + { + ErrorCode result; + IntPtr size; + + result = (ErrorCode)OpenCL.GetGLTextureInfo(Mem.MemID, key, IntPtr.Zero, null, out size); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("GetGLTextureInfo failed with error code " + result, result); + + return size; + } + + public void ReadProperty(uint key, IntPtr keyLength, void* pBuffer) + { + ErrorCode result; + IntPtr size; + + result = (ErrorCode)OpenCL.GetGLTextureInfo(Mem.MemID, key, keyLength, pBuffer, out size); + if (result != ErrorCode.SUCCESS) + throw new OpenCLException("GetGLTextureInfo failed with error code " + result, result); + } + + #endregion + } + + } +} diff --git a/OpenCLNet/OpenCL.cs b/OpenCLNet/OpenCL.cs new file mode 100644 index 0000000..dda74b4 --- /dev/null +++ b/OpenCLNet/OpenCL.cs @@ -0,0 +1,617 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Text; + +namespace OpenCLNet +{ + #region Using statements + + using cl_char = SByte; + using cl_uchar = Byte; + using cl_short = Byte; + using cl_ushort = Byte; + using cl_int = Int32; + using cl_uint = UInt32; + using cl_long = Int64; + using cl_ulong = UInt64; + using cl_half = UInt16; + using cl_float = Single; + using cl_double = Double; + + using cl_platform_id = IntPtr; + using cl_device_id = IntPtr; + using cl_context = IntPtr; + using cl_command_queue = IntPtr; + using cl_mem = IntPtr; + using cl_program = IntPtr; + using cl_kernel = IntPtr; + using cl_event = IntPtr; + using cl_sampler = IntPtr; + + using cl_bool = UInt32; + using cl_bitfield = UInt64; + using cl_device_type = UInt64; + using cl_platform_info = UInt32; + using cl_device_info = UInt32; + using cl_device_address_info = UInt64; + using cl_device_fp_config = UInt64; + using cl_device_mem_cache_type = UInt32; + using cl_device_local_mem_type = UInt32; + using cl_device_exec_capabilities = UInt64; + using cl_command_queue_properties = UInt64; + + using cl_context_properties = IntPtr; + using cl_context_info = UInt32; + using cl_command_queue_info = UInt32; + using cl_channel_order = UInt32; + using cl_channel_type = UInt32; + using cl_mem_flags = UInt64; + using cl_mem_object_type = UInt32; + using cl_mem_info = UInt32; + using cl_image_info = UInt32; + using cl_addressing_mode = UInt32; + using cl_filter_mode = UInt32; + using cl_sampler_info = UInt32; + using cl_map_flags = UInt64; + using cl_program_info = UInt32; + using cl_program_build_info = UInt32; + using cl_build_status = Int32; + using cl_kernel_info = UInt32; + using cl_kernel_work_group_info = UInt32; + using cl_event_info = UInt32; + using cl_command_type = UInt32; + using cl_profiling_info = UInt32; + + using cl_gl_object_type = UInt32; + using cl_gl_texture_info = UInt32; + using cl_gl_platform_info = UInt32; + using GLuint = UInt32; + using GLint = Int32; + using GLenum = Int32; + #endregion + + public delegate void ContextNotify(string errInfo, byte[] data, IntPtr cb, IntPtr userData); + public delegate void ProgramNotify(cl_program program, IntPtr userData); + public delegate void NativeKernel(IntPtr args); + + public unsafe static class OpenCL + { + static Dictionary _Platforms = new Dictionary(); + static IntPtr[] PlatformIDs; + static Platform[] Platforms; + + static OpenCL() + { + try + { + Initialize(); + } + catch (Exception) + { + _Platforms.Clear(); + PlatformIDs = new IntPtr[0]; + Platforms = new Platform[0]; + } + } + + private static void Initialize() + { + PlatformIDs = GetPlatformIDs(); + if (PlatformIDs == null) + return; + + Platforms = new Platform[PlatformIDs.Length]; + for (int i = 0; i < PlatformIDs.Length; i++) + { + Platform p; + + p = new Platform(PlatformIDs[i]); + Platforms[i] = p; + _Platforms[PlatformIDs[i]] = p; + } + } + + public static int NumberOfPlatforms + { + get { return _Platforms.Count; } + } + + public static Platform[] GetPlatforms() + { + return (Platform[])Platforms.Clone(); + } + + public static Platform GetPlatform(int index) + { + return _Platforms[PlatformIDs[index]]; + } + + public static Platform GetPlatform(IntPtr platformID) + { + return _Platforms[platformID]; + } + + unsafe static private IntPtr[] GetPlatformIDs() + { + IntPtr[] platformIDs; + ErrorCode result; + uint returnedPlatforms; + + result = (ErrorCode)GetPlatformIDs(0, null, out returnedPlatforms); + if (result == ErrorCode.INVALID_VALUE) + return null; + + platformIDs = new IntPtr[returnedPlatforms]; + result = (ErrorCode)GetPlatformIDs((uint)platformIDs.Length, platformIDs, out returnedPlatforms); + if (result == ErrorCode.INVALID_VALUE) + return null; + return platformIDs; + } + + + + + + #region Platform API + + public static ErrorCode GetPlatformIDs(uint num_entries, IntPtr[] platforms, out uint num_platforms) + { + return (ErrorCode)OpenCLAPI.clGetPlatformIDs(num_entries, platforms, out num_platforms); + } + + public static ErrorCode GetPlatformInfo(IntPtr platform, uint param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret) + { + return (ErrorCode)OpenCLAPI.clGetPlatformInfo(platform, param_name, param_value_size, param_value, out param_value_size_ret); + } + + #endregion + + #region Device API + + public static ErrorCode GetDeviceIDs(IntPtr platform, DeviceType device_type, uint num_entries, IntPtr[] devices, out uint num_devices) + { + return (ErrorCode)OpenCLAPI.clGetDeviceIDs(platform, device_type, num_entries, devices, out num_devices); + } + + public static ErrorCode GetDeviceInfo(IntPtr device, uint param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret) + { + return (ErrorCode)OpenCLAPI.clGetDeviceInfo(device, param_name, param_value_size, param_value, out param_value_size_ret); + } + + #endregion + + #region Context API + + public static IntPtr CreateContext(IntPtr[] properties, uint num_devices, IntPtr[] devices, ContextNotify pfn_notify, IntPtr user_data, out ErrorCode errcode_ret) + { + return OpenCLAPI.clCreateContext(properties, num_devices, devices, pfn_notify, user_data, out errcode_ret); + } + + public static IntPtr CreateContextFromType(IntPtr[] properties, DeviceType device_type, ContextNotify pfn_notify, IntPtr user_data, out ErrorCode errcode_ret) + { + return OpenCLAPI.clCreateContextFromType(properties, device_type, pfn_notify, user_data, out errcode_ret); + } + + public static ErrorCode RetainContext(IntPtr context) + { + return (ErrorCode)OpenCLAPI.clRetainContext(context); + } + + public static ErrorCode ReleaseContext(IntPtr context) + { + return (ErrorCode)OpenCLAPI.clReleaseContext(context); + } + + public static ErrorCode GetContextInfo(IntPtr context, uint param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret) + { + return (ErrorCode)OpenCLAPI.clGetContextInfo(context, param_name, param_value_size, param_value, out param_value_size_ret); + } + + #endregion + + #region Program Object API + + public static IntPtr CreateProgramWithSource(IntPtr context, uint count, string[] strings, IntPtr[] lengths, out ErrorCode errcode_ret) + { + return OpenCLAPI.clCreateProgramWithSource(context, count, strings, lengths, out errcode_ret); + } + + public static IntPtr CreateProgramWithBinary(IntPtr context, uint num_devices, IntPtr[] device_list, IntPtr[] lengths, byte[][] binaries, int[] binary_status, out ErrorCode errcode_ret) + { + IntPtr program; + + program = OpenCLAPI.clCreateProgramWithBinary(context, num_devices, device_list, lengths, binaries, binary_status, out errcode_ret); + return program; + } + + public static ErrorCode RetainProgram(IntPtr program) + { + return (ErrorCode)OpenCLAPI.clRetainProgram(program); + } + + public static ErrorCode ReleaseProgram(IntPtr program) + { + return (ErrorCode)OpenCLAPI.clReleaseProgram(program); + } + + public static ErrorCode BuildProgram(IntPtr program, uint num_devices, IntPtr[] device_list, string options, ProgramNotify pfn_notify, IntPtr user_data) + { + return (ErrorCode)OpenCLAPI.clBuildProgram(program, num_devices, device_list, options, pfn_notify, user_data); + } + + public static ErrorCode UnloadCompiler() + { + return (ErrorCode)OpenCLAPI.clUnloadCompiler(); + } + + public static ErrorCode GetProgramInfo(IntPtr program, uint param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret) + { + return (ErrorCode)OpenCLAPI.clGetProgramInfo(program, param_name, param_value_size, param_value, out param_value_size_ret); + } + + public static ErrorCode GetProgramBuildInfo(IntPtr program, IntPtr device, uint param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret) + { + return (ErrorCode)OpenCLAPI.clGetProgramBuildInfo(program, device, param_name, param_value_size, param_value, out param_value_size_ret); + } + + #endregion + + #region Command Queue API + + public static IntPtr CreateCommandQueue(IntPtr context, IntPtr device, ulong properties, out ErrorCode errcode_ret) + { + return OpenCLAPI.clCreateCommandQueue(context, device, properties, out errcode_ret); + } + + public static ErrorCode RetainCommandQueue(IntPtr command_queue) + { + return OpenCLAPI.clRetainCommandQueue(command_queue); + } + + public static ErrorCode ReleaseCommandQueue(IntPtr command_queue) + { + return OpenCLAPI.clReleaseCommandQueue(command_queue); + } + + public static ErrorCode GetCommandQueueInfo(IntPtr command_queue, uint param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret) + { + return OpenCLAPI.clGetCommandQueueInfo(command_queue, param_name, param_value_size, param_value, out param_value_size_ret); + } + + public static ErrorCode SetCommandQueueProperty(IntPtr command_queue, ulong properties, bool enable, out ulong old_properties) + { + return OpenCLAPI.clSetCommandQueueProperty(command_queue, properties, enable, out old_properties); + } + + #endregion + + #region Memory Object API + + public static IntPtr CreateBuffer(IntPtr context, ulong flags, IntPtr size, void* host_ptr, out ErrorCode errcode_ret) + { + return OpenCLAPI.clCreateBuffer(context, flags, size, host_ptr, out errcode_ret); + } + + public static IntPtr CreateImage2D(IntPtr context, ulong flags, ImageFormat image_format, IntPtr image_width, IntPtr image_height, IntPtr image_row_pitch, void* host_ptr, out ErrorCode errcode_ret) + { + return OpenCLAPI.clCreateImage2D(context, flags, &image_format, image_width, image_height, image_row_pitch, host_ptr, out errcode_ret); + } + + public static IntPtr CreateImage3D(IntPtr context, ulong flags, ImageFormat image_format, IntPtr image_width, IntPtr image_height, IntPtr image_depth, IntPtr image_row_pitch, IntPtr image_slice_pitch, void* host_ptr, out ErrorCode errcode_ret) + { + return OpenCLAPI.clCreateImage3D(context, flags, &image_format, image_width, image_height, image_depth, image_row_pitch, image_slice_pitch, host_ptr, out errcode_ret); + } + + public static ErrorCode RetainMemObject(IntPtr memobj) + { + return OpenCLAPI.clRetainMemObject(memobj); + } + + public static ErrorCode ReleaseMemObject(IntPtr memobj) + { + return OpenCLAPI.clReleaseMemObject(memobj); + } + + public static ErrorCode GetSupportedImageFormats(IntPtr context, ulong flags, uint image_type, uint num_entries, ImageFormat[] image_formats, out uint num_image_formats) + { + return OpenCLAPI.clGetSupportedImageFormats(context, flags, image_type, num_entries, image_formats, out num_image_formats); + } + + public static ErrorCode GetMemObjectInfo(IntPtr memobj, uint param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret) + { + return OpenCLAPI.clGetMemObjectInfo(memobj, param_name, param_value_size, param_value, out param_value_size_ret); + } + + public static ErrorCode GetImageInfo(IntPtr image, uint param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret) + { + return OpenCLAPI.clGetImageInfo(image, param_name, param_value_size, param_value, out param_value_size_ret); + } + + #endregion + + #region Kernel Object API + + public static cl_kernel CreateKernel(IntPtr program, string kernel_name, out ErrorCode errcode_ret) + { + return OpenCLAPI.clCreateKernel(program, kernel_name, out errcode_ret); + } + + public static ErrorCode CreateKernelsInProgram(IntPtr program, uint num_kernels, IntPtr[] kernels, out uint num_kernels_ret) + { + return OpenCLAPI.clCreateKernelsInProgram(program, num_kernels, kernels, out num_kernels_ret); + } + + public static ErrorCode RetainKernel(IntPtr kernel) + { + return OpenCLAPI.clRetainKernel(kernel); + } + + public static ErrorCode ReleaseKernel(IntPtr kernel) + { + return OpenCLAPI.clReleaseKernel(kernel); + } + + public static ErrorCode SetKernelArg(IntPtr kernel, uint arg_index, IntPtr arg_size, void* arg_value) + { + return OpenCLAPI.clSetKernelArg(kernel, arg_index, arg_size, arg_value); + } + + public static ErrorCode GetKernelInfo(IntPtr kernel, uint param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret) + { + return OpenCLAPI.clGetKernelInfo(kernel, param_name, param_value_size, param_value, out param_value_size_ret); + } + + public static ErrorCode GetKernelWorkGroupInfo(IntPtr kernel, IntPtr device, uint param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret) + { + return OpenCLAPI.clGetKernelWorkGroupInfo(kernel, device, param_name, param_value_size, param_value, out param_value_size_ret); + } + + #endregion + + #region Enqueued Commands API + + public static ErrorCode EnqueueReadBuffer(IntPtr command_queue, IntPtr buffer, uint blocking_read, IntPtr offset, IntPtr cb, void* ptr, uint num_events_in_wait_list, IntPtr[] event_wait_list, IntPtr* _event) + { + return OpenCLAPI.clEnqueueReadBuffer(command_queue, buffer, blocking_read, offset, cb, ptr, num_events_in_wait_list, event_wait_list, _event); + } + + public static ErrorCode EnqueueWriteBuffer(IntPtr command_queue, IntPtr buffer, uint blocking_write, IntPtr offset, IntPtr cb, void* ptr, uint num_events_in_wait_list, IntPtr[] event_wait_list, IntPtr* _event) + { + return OpenCLAPI.clEnqueueWriteBuffer(command_queue, buffer, blocking_write, offset, cb, ptr, num_events_in_wait_list, event_wait_list, _event); + } + + public static ErrorCode EnqueueCopyBuffer(IntPtr command_queue, IntPtr src_buffer, IntPtr dst_buffer, IntPtr src_offset, IntPtr dst_offset, IntPtr cb, uint num_events_in_wait_list, IntPtr[] event_wait_list, IntPtr* _event) + { + return OpenCLAPI.clEnqueueCopyBuffer(command_queue, src_buffer, dst_buffer, src_offset, dst_offset, cb, num_events_in_wait_list, event_wait_list, _event); + } + + public static ErrorCode EnqueueReadImage(IntPtr command_queue, IntPtr image, uint blocking_read, IntPtr[] origin, IntPtr[] region, IntPtr row_pitch, IntPtr slice_pitch, void* ptr, uint num_events_in_wait_list, IntPtr[] event_wait_list, IntPtr* _event) + { + return OpenCLAPI.clEnqueueReadImage(command_queue, image, blocking_read, origin, region, row_pitch, slice_pitch, ptr, num_events_in_wait_list, event_wait_list, _event); + } + + public static ErrorCode EnqueueWriteImage(IntPtr command_queue, IntPtr image, uint blocking_write, IntPtr[] origin, IntPtr[] region, IntPtr input_row_pitch, IntPtr input_slice_pitch, void* ptr, uint num_events_in_wait_list, IntPtr[] event_wait_list, IntPtr* _event) + { + return OpenCLAPI.clEnqueueWriteImage(command_queue, image, blocking_write, origin, region, input_row_pitch, input_slice_pitch, ptr, num_events_in_wait_list, event_wait_list, _event); + } + + public static ErrorCode EnqueueCopyImage(IntPtr command_queue, IntPtr src_image, IntPtr dst_image, IntPtr[] src_origin, IntPtr[] dst_origin, IntPtr[] region, uint num_events_in_wait_list, IntPtr[] event_wait_list, IntPtr* _event) + { + return OpenCLAPI.clEnqueueCopyImage(command_queue, src_image, dst_image, src_origin, dst_origin, region, num_events_in_wait_list, event_wait_list, _event); + } + + public static ErrorCode EnqueueCopyImageToBuffer(IntPtr command_queue, IntPtr src_image, IntPtr dst_buffer, IntPtr[] src_origin, IntPtr[] region, IntPtr dst_offset, uint num_events_in_wait_list, IntPtr[] event_wait_list, IntPtr* _event) + { + return OpenCLAPI.clEnqueueCopyImageToBuffer(command_queue, src_image, dst_buffer, src_origin, region, dst_offset, num_events_in_wait_list, event_wait_list, _event); + } + + public static ErrorCode EnqueueCopyBufferToImage(IntPtr command_queue, IntPtr src_buffer, IntPtr dst_image, IntPtr src_offset, IntPtr[] dst_origin, IntPtr[] region, uint num_events_in_wait_list, IntPtr[] event_wait_list, IntPtr* _event) + { + return OpenCLAPI.clEnqueueCopyBufferToImage(command_queue, src_buffer, dst_image, src_offset, dst_origin, region, num_events_in_wait_list, event_wait_list, _event); + } + + public static void* EnqueueMapBuffer(IntPtr command_queue, IntPtr buffer, uint blocking_map, ulong map_flags, IntPtr offset, IntPtr cb, uint num_events_in_wait_list, IntPtr[] event_wait_list, IntPtr* _event, out ErrorCode errcode_ret) + { + return OpenCLAPI.clEnqueueMapBuffer(command_queue, buffer, blocking_map, map_flags, offset, cb, num_events_in_wait_list, event_wait_list, _event, out errcode_ret); + } + + public static void* EnqueueMapImage(IntPtr command_queue, IntPtr image, uint blocking_map, ulong map_flags, IntPtr[] origin, IntPtr[] region, out IntPtr image_row_pitch, out IntPtr image_slice_pitch, uint num_events_in_wait_list, IntPtr[] event_wait_list, IntPtr* _event, out ErrorCode errcode_ret) + { + return OpenCLAPI.clEnqueueMapImage(command_queue, image, blocking_map, map_flags, origin, region, out image_row_pitch, out image_slice_pitch, num_events_in_wait_list, event_wait_list, _event, out errcode_ret); + } + + public static ErrorCode EnqueueUnmapMemObject(IntPtr command_queue, IntPtr memobj, void* mapped_ptr, uint num_events_in_wait_list, IntPtr[] event_wait_list, IntPtr* _event) + { + return OpenCLAPI.clEnqueueUnmapMemObject(command_queue, memobj, mapped_ptr, num_events_in_wait_list, event_wait_list, _event); + } + + public static ErrorCode EnqueueNDRangeKernel(IntPtr command_queue, IntPtr kernel, uint work_dim, IntPtr[] global_work_offset, IntPtr[] global_work_size, IntPtr[] local_work_size, uint num_events_in_wait_list, IntPtr[] event_wait_list, IntPtr* _event) + { + return OpenCLAPI.clEnqueueNDRangeKernel(command_queue, kernel, work_dim, global_work_offset, global_work_size, local_work_size, num_events_in_wait_list, event_wait_list, _event); + } + + public static ErrorCode EnqueueTask(IntPtr command_queue, IntPtr kernel, uint num_events_in_wait_list, IntPtr[] event_wait_list, IntPtr* _event) + { + return OpenCLAPI.clEnqueueTask(command_queue, kernel, num_events_in_wait_list, event_wait_list, _event); + } + + public static ErrorCode EnqueueNativeKernel(cl_command_queue command_queue, + NativeKernel user_func, + void* args, + IntPtr cb_args, + cl_uint num_mem_objects, + cl_mem[] mem_list, + IntPtr[] args_mem_loc, + cl_uint num_events_in_wait_list, + cl_event[] event_wait_list, + cl_event* _event) + { + return OpenCLAPI.clEnqueueNativeKernel(command_queue, + user_func, + args, + cb_args, + num_mem_objects, + mem_list, + args_mem_loc, + num_events_in_wait_list, + event_wait_list, + _event); + } + + public static ErrorCode EnqueueMarker(IntPtr command_queue, IntPtr* _event) + { + return OpenCLAPI.clEnqueueMarker(command_queue, _event); + } + + public static ErrorCode EnqueueWaitForEvents(IntPtr command_queue, uint num_events, IntPtr[] _event_list) + { + return OpenCLAPI.clEnqueueWaitForEvents(command_queue, num_events, _event_list); + } + + public static ErrorCode EnqueueBarrier(IntPtr command_queue) + { + return OpenCLAPI.clEnqueueBarrier(command_queue); + } + + #endregion + + #region Flush and Finish API + + public static ErrorCode Flush(cl_command_queue command_queue) + { + return OpenCLAPI.clFlush(command_queue); + } + + public static ErrorCode Finish(cl_command_queue command_queue) + { + return OpenCLAPI.clFinish(command_queue); + } + + #endregion + + #region Event Object API + + public static ErrorCode WaitForEvents(cl_uint num_events, cl_event[] _event_list) + { + return OpenCLAPI.clWaitForEvents(num_events, _event_list); + } + + public static ErrorCode GetEventInfo(cl_event _event, cl_event_info param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret) + { + return OpenCLAPI.clGetEventInfo(_event, param_name, param_value_size, param_value, out param_value_size_ret); + } + + public static ErrorCode RetainEvent(cl_event _event) + { + return OpenCLAPI.clRetainEvent(_event); + } + + public static ErrorCode ReleaseEvent(cl_event _event) + { + return OpenCLAPI.clReleaseEvent(_event); + } + + #endregion + + #region Sampler API + + public static cl_sampler CreateSampler(cl_context context, bool normalized_coords, cl_addressing_mode addressing_mode, cl_filter_mode filter_mode, out ErrorCode errcode_ret) + { + return OpenCLAPI.clCreateSampler(context, normalized_coords ? (cl_bool)Bool.TRUE : (cl_bool)Bool.FALSE, addressing_mode, filter_mode, out errcode_ret); + } + + public static ErrorCode RetainSampler(cl_sampler sampler) + { + return OpenCLAPI.clRetainSampler(sampler); + } + + public static ErrorCode ReleaseSampler(cl_sampler sampler) + { + return OpenCLAPI.clReleaseSampler(sampler); + } + + public static ErrorCode GetSamplerInfo(cl_sampler sampler, cl_sampler_info param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret) + { + return OpenCLAPI.clGetSamplerInfo(sampler, param_name, param_value_size, param_value, out param_value_size_ret); + } + + #endregion + + #region GLObject API + + public static cl_mem CreateFromGLBuffer(cl_context context, cl_mem_flags flags, GLuint bufobj, out ErrorCode errcode_ret) + { + return OpenCLAPI.clCreateFromGLBuffer(context, flags, bufobj, out errcode_ret); + } + public static cl_mem CreateFromGLTexture2D(cl_context context, cl_mem_flags flags, GLenum target, GLint mipLevel, GLuint texture, out ErrorCode errcode_ret) + { + return OpenCLAPI.clCreateFromGLTexture2D(context, flags, target, mipLevel, texture, out errcode_ret); + } + public static cl_mem CreateFromGLTexture3D(cl_context context, cl_mem_flags flags, GLenum target, GLint mipLevel, GLuint texture, out ErrorCode errcode_ret) + { + return OpenCLAPI.clCreateFromGLTexture3D(context, flags, target, mipLevel, texture, out errcode_ret); + } + public static cl_mem CreateFromGLRenderbuffer(cl_context context, cl_mem_flags flags, GLuint renderbuffer, out ErrorCode errcode_ret) + { + return OpenCLAPI.clCreateFromGLRenderbuffer(context, flags, renderbuffer, out errcode_ret); + } + public static ErrorCode GetGLObjectInfo(cl_mem memobj, out cl_gl_object_type gl_object_type, out GLuint gl_object_name) + { + return OpenCLAPI.clGetGLObjectInfo(memobj, out gl_object_type, out gl_object_name); + } + public static ErrorCode GetGLTextureInfo(cl_mem memobj, cl_gl_texture_info param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret) + { + return OpenCLAPI.clGetGLTextureInfo(memobj, param_name, param_value_size, param_value, out param_value_size_ret); + } + public static ErrorCode EnqueueAcquireGLObjects(cl_command_queue command_queue, cl_uint num_objects, cl_mem[] mem_objects, cl_uint num_events_in_wait_list, cl_event[] event_wait_list, cl_event* _event) + { + return OpenCLAPI.clEnqueueAcquireGLObjects(command_queue, num_objects, mem_objects, num_events_in_wait_list, event_wait_list, _event); + } + public static ErrorCode EnqueueReleaseGLObjects(cl_command_queue command_queue, cl_uint num_objects, cl_mem[] mem_objects, cl_uint num_events_in_wait_list, cl_event[] event_wait_list, cl_event* _event) + { + return OpenCLAPI.clEnqueueAcquireGLObjects(command_queue, num_objects, mem_objects, num_events_in_wait_list, event_wait_list, _event); + } + + #endregion + + + // Extension function access + public static IntPtr GetExtensionFunctionAddress(string func_name) + { + return OpenCLAPI.clGetExtensionFunctionAddress(func_name); + } + + public static ErrorCode GetEventProfilingInfo(cl_event _event, ProfilingInfo param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret) + { + return (ErrorCode)OpenCLAPI.clGetEventProfilingInfo(_event, (uint)param_name, param_value_size, param_value, out param_value_size_ret); + } + } +} diff --git a/OpenCLNet/OpenCLAPI.cs b/OpenCLNet/OpenCLAPI.cs new file mode 100644 index 0000000..4398cf3 --- /dev/null +++ b/OpenCLNet/OpenCLAPI.cs @@ -0,0 +1,514 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Runtime.InteropServices; +using System.Diagnostics; +using System.Security; + +namespace OpenCLNet +{ + #region Using statements + + using cl_char=SByte; + using cl_uchar=Byte; + using cl_short=Byte; + using cl_ushort=Byte; + using cl_int=Int32; + using cl_uint=UInt32; + using cl_long=Int64; + using cl_ulong=UInt64; + using cl_half=UInt16; + using cl_float=Single; + using cl_double=Double; + + using cl_platform_id=IntPtr; + using cl_device_id=IntPtr; + using cl_context=IntPtr; + using cl_command_queue=IntPtr; + using cl_mem=IntPtr; + using cl_program=IntPtr; + using cl_kernel=IntPtr; + using cl_event=IntPtr; + using cl_sampler=IntPtr; + + using cl_bool=UInt32; + using cl_bitfield=UInt64; + using cl_device_type=UInt64; + using cl_platform_info=UInt32; + using cl_device_info=UInt32; + using cl_device_address_info=UInt64; + using cl_device_fp_config=UInt64; + using cl_device_mem_cache_type=UInt32; + using cl_device_local_mem_type=UInt32; + using cl_device_exec_capabilities=UInt64; + using cl_command_queue_properties=UInt64; + + using cl_context_properties=IntPtr; + using cl_context_info=UInt32; + using cl_command_queue_info=UInt32; + using cl_channel_order=UInt32; + using cl_channel_type=UInt32; + using cl_mem_flags=UInt64; + using cl_mem_object_type=UInt32; + using cl_mem_info=UInt32; + using cl_image_info=UInt32; + using cl_addressing_mode=UInt32; + using cl_filter_mode=UInt32; + using cl_sampler_info=UInt32; + using cl_map_flags=UInt64; + using cl_program_info=UInt32; + using cl_program_build_info=UInt32; + using cl_build_status=Int32; + using cl_kernel_info=UInt32; + using cl_kernel_work_group_info=UInt32; + using cl_event_info=UInt32; + using cl_command_type=UInt32; + using cl_profiling_info=UInt32; + + using cl_gl_object_type=UInt32; + using cl_gl_texture_info=UInt32; + using cl_gl_platform_info=UInt32; + using cl_gl_context_info=UInt32; + using GLuint=UInt32; + using GLint=Int32; + using GLenum=Int32; + #endregion + + /// + /// OpenCLAPI - native bindings + /// + [SuppressUnmanagedCodeSecurity()] + unsafe public static class OpenCLAPI + { + internal static class Configuration + { + public const string Library = "opencl.dll"; + } + + #region Platform API + + // Platform API + [DllImport(Configuration.Library)] + public extern static cl_int clGetPlatformIDs(cl_uint num_entries, [Out] [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] cl_platform_id[] platforms, out cl_uint num_platforms); + + [DllImport(Configuration.Library)] + public extern static cl_int clGetPlatformInfo(cl_platform_id platform, cl_platform_info param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret); + + #endregion + + #region Device API + + // Device APIs + [DllImport(Configuration.Library)] + public extern static cl_int clGetDeviceIDs(cl_platform_id platform, [MarshalAs(UnmanagedType.U8)]DeviceType device_type, cl_uint num_entries, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)]cl_device_id[] devices, out cl_uint num_devices); + + [DllImport(Configuration.Library)] + public extern static cl_int clGetDeviceInfo(cl_device_id device, cl_device_info param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret); + + #endregion + + #region Context API + + // Context APIs + [DllImport(Configuration.Library)] + public extern static cl_context clCreateContext([In] cl_context_properties[] properties, cl_uint num_devices, [In]cl_device_id[] devices, ContextNotify pfn_notify, IntPtr user_data, [MarshalAs(UnmanagedType.I4)] out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static cl_context clCreateContextFromType([In] cl_context_properties[] properties, [MarshalAs(UnmanagedType.U8)]DeviceType device_type, ContextNotify pfn_notify, IntPtr user_data, [MarshalAs(UnmanagedType.I4)] out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static cl_int clRetainContext(cl_context context); + [DllImport(Configuration.Library)] + public extern static cl_int clReleaseContext(cl_context context); + [DllImport(Configuration.Library)] + public extern static cl_int clGetContextInfo(cl_context context, cl_context_info param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret); + + #endregion + + #region Program Object API + + // Program Object APIs + [DllImport(Configuration.Library)] + public extern static cl_program clCreateProgramWithSource(cl_context context, + cl_uint count, + [In] string[] strings, + [In] IntPtr[] lengths, + [MarshalAs(UnmanagedType.I4)] out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static cl_program clCreateProgramWithBinary(cl_context context, + cl_uint num_devices, + [In] cl_device_id[] device_list, + [In] IntPtr[] lengths, + [In] byte[][] binaries, + [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] cl_int[] binary_status, + [MarshalAs(UnmanagedType.I4)] out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static cl_int clRetainProgram(cl_program program); + [DllImport(Configuration.Library)] + public extern static cl_int clReleaseProgram(cl_program program); + [DllImport(Configuration.Library)] + public extern static cl_int clBuildProgram(cl_program program, + cl_uint num_devices, + [In] cl_device_id[] device_list, + string options, + ProgramNotify pfn_notify, + IntPtr user_data); + [DllImport(Configuration.Library)] + public extern static cl_int clUnloadCompiler(); + [DllImport(Configuration.Library)] + public extern static cl_int clGetProgramInfo(cl_program program, cl_program_info param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret); + [DllImport(Configuration.Library)] + public extern static cl_int clGetProgramBuildInfo(cl_program program, cl_device_id device, cl_program_build_info param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret); + + #endregion + + #region Command Queue API + + // Command Queue APIs + [DllImport(Configuration.Library)] + public extern static IntPtr clCreateCommandQueue(cl_context context, cl_device_id device, cl_command_queue_properties properties, [MarshalAs(UnmanagedType.I4)] out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static ErrorCode clRetainCommandQueue(cl_command_queue command_queue); + [DllImport(Configuration.Library)] + public extern static ErrorCode clReleaseCommandQueue(cl_command_queue command_queue); + [DllImport(Configuration.Library)] + public extern static ErrorCode clGetCommandQueueInfo(cl_command_queue command_queue, cl_command_queue_info param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret); + [DllImport(Configuration.Library)] + public extern static ErrorCode clSetCommandQueueProperty(cl_command_queue command_queue, cl_command_queue_properties properties, [MarshalAs(UnmanagedType.I4)]bool enable, out cl_command_queue_properties old_properties); + + #endregion + + #region Memory Object API + + // Memory Object APIs + [DllImport(Configuration.Library)] + public extern static cl_mem clCreateBuffer(cl_context context, cl_mem_flags flags, IntPtr size, void* host_ptr, out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static cl_mem clCreateImage2D(cl_context context, cl_mem_flags flags, ImageFormat* image_format, IntPtr image_width, IntPtr image_height, IntPtr image_row_pitch, void* host_ptr, out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static cl_mem clCreateImage3D(cl_context context, cl_mem_flags flags, ImageFormat* image_format, IntPtr image_width, IntPtr image_height, IntPtr image_depth, IntPtr image_row_pitch, IntPtr image_slice_pitch, void* host_ptr, out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static ErrorCode clRetainMemObject(cl_mem memobj); + [DllImport(Configuration.Library)] + public extern static ErrorCode clReleaseMemObject(cl_mem memobj); + [DllImport(Configuration.Library)] + public extern static ErrorCode clGetSupportedImageFormats(cl_context context, + cl_mem_flags flags, + cl_mem_object_type image_type, + cl_uint num_entries, + [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] ImageFormat[] image_formats, + out cl_uint num_image_formats); + [DllImport(Configuration.Library)] + public extern static ErrorCode clGetMemObjectInfo(cl_mem memobj, cl_mem_info param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret); + [DllImport(Configuration.Library)] + public extern static ErrorCode clGetImageInfo(cl_mem image, cl_image_info param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret); + + #endregion + + #region Kernel Object API + + // Kernel Object APIs + [DllImport(Configuration.Library)] + public extern static cl_kernel clCreateKernel(cl_program program, string kernel_name, out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static ErrorCode clCreateKernelsInProgram(cl_program program, + cl_uint num_kernels, + [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]cl_kernel[] kernels, + out cl_uint num_kernels_ret); + [DllImport(Configuration.Library)] + public extern static ErrorCode clRetainKernel(cl_kernel kernel); + [DllImport(Configuration.Library)] + public extern static ErrorCode clReleaseKernel(cl_kernel kernel); + [DllImport(Configuration.Library)] + public extern static ErrorCode clSetKernelArg(cl_kernel kernel, cl_uint arg_index, IntPtr arg_size, void* arg_value); + [DllImport(Configuration.Library)] + public extern static ErrorCode clGetKernelInfo(cl_kernel kernel, cl_kernel_info param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret); + [DllImport(Configuration.Library)] + public extern static ErrorCode clGetKernelWorkGroupInfo(cl_kernel kernel, cl_device_id device, cl_kernel_work_group_info param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret); + + #endregion + + #region Enqueued Commands API + + // Enqueued Commands APIs + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueReadBuffer(cl_command_queue command_queue, + cl_mem buffer, + cl_bool blocking_read, + IntPtr offset, + IntPtr cb, + void* ptr, + cl_uint num_events_in_wait_list, + [In] [MarshalAs(UnmanagedType.LPArray)] cl_event[] event_wait_list, + cl_event* _event); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueWriteBuffer(cl_command_queue command_queue, + cl_mem buffer, + cl_bool blocking_write, + IntPtr offset, + IntPtr cb, + void* ptr, + cl_uint num_events_in_wait_list, + [In] [MarshalAs(UnmanagedType.LPArray)] cl_event[] event_wait_list, + cl_event* _event); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueCopyBuffer(cl_command_queue command_queue, + cl_mem src_buffer, + cl_mem dst_buffer, + IntPtr src_offset, + IntPtr dst_offset, + IntPtr cb, + cl_uint num_events_in_wait_list, + [In] [MarshalAs(UnmanagedType.LPArray)] cl_event[] event_wait_list, + cl_event* _event); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueReadImage(cl_command_queue command_queue, + cl_mem image, + cl_bool blocking_read, + IntPtr[] origin, + IntPtr[] region, + IntPtr row_pitch, + IntPtr slice_pitch, + void* ptr, + cl_uint num_events_in_wait_list, + [In] [MarshalAs(UnmanagedType.LPArray)] cl_event[] event_wait_list, + cl_event* _event); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueWriteImage(cl_command_queue command_queue, + cl_mem image, + cl_bool blocking_write, + IntPtr[] origin, + IntPtr[] region, + IntPtr input_row_pitch, + IntPtr input_slice_pitch, + void* ptr, + cl_uint num_events_in_wait_list, + [In] [MarshalAs(UnmanagedType.LPArray)] cl_event[] event_wait_list, + cl_event* _event); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueCopyImage(cl_command_queue command_queue, + cl_mem src_image, + cl_mem dst_image, + IntPtr[] src_origin, + IntPtr[] dst_origin, + IntPtr[] region, + cl_uint num_events_in_wait_list, + [In] [MarshalAs(UnmanagedType.LPArray)] cl_event[] event_wait_list, + cl_event* _event); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueCopyImageToBuffer(cl_command_queue command_queue, + cl_mem src_image, + cl_mem dst_buffer, + IntPtr[] src_origin, + IntPtr[] region, + IntPtr dst_offset, + cl_uint num_events_in_wait_list, + [In] [MarshalAs(UnmanagedType.LPArray)] cl_event[] event_wait_list, + cl_event* _event); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueCopyBufferToImage(cl_command_queue command_queue, + cl_mem src_buffer, + cl_mem dst_image, + IntPtr src_offset, + IntPtr[] dst_origin, + IntPtr[] region, + cl_uint num_events_in_wait_list, + [In] [MarshalAs(UnmanagedType.LPArray)] cl_event[] event_wait_list, + cl_event* _event); + [DllImport(Configuration.Library)] + public extern static void* clEnqueueMapBuffer(cl_command_queue command_queue, + cl_mem buffer, + cl_bool blocking_map, + cl_map_flags map_flags, + IntPtr offset, + IntPtr cb, + cl_uint num_events_in_wait_list, + [In] [MarshalAs(UnmanagedType.LPArray)] cl_event[] event_wait_list, + cl_event* _event, + out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static void* clEnqueueMapImage(cl_command_queue command_queue, + cl_mem image, + cl_bool blocking_map, + cl_map_flags map_flags, + IntPtr[] origin, + IntPtr[] region, + out IntPtr image_row_pitch, + out IntPtr image_slice_pitch, + cl_uint num_events_in_wait_list, + [In] [MarshalAs(UnmanagedType.LPArray)] cl_event[] event_wait_list, + cl_event* _event, + out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueUnmapMemObject(cl_command_queue command_queue, + cl_mem memobj, + void* mapped_ptr, + cl_uint num_events_in_wait_list, + [In] [MarshalAs(UnmanagedType.LPArray)] cl_event[] event_wait_list, + cl_event* _event); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueNDRangeKernel(cl_command_queue command_queue, + cl_kernel kernel, + cl_uint work_dim, + [In] [MarshalAs(UnmanagedType.LPArray)] IntPtr[] global_work_offset, + [In] [MarshalAs(UnmanagedType.LPArray)] IntPtr[] global_work_size, + [In] [MarshalAs(UnmanagedType.LPArray)] IntPtr[] local_work_size, + cl_uint num_events_in_wait_list, + [In] [MarshalAs(UnmanagedType.LPArray)] cl_event[] event_wait_list, + cl_event* _event); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueTask(cl_command_queue command_queue, + cl_kernel kernel, + cl_uint num_events_in_wait_list, + [In] [MarshalAs(UnmanagedType.LPArray)] cl_event[] event_wait_list, + cl_event* _event); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueNativeKernel(cl_command_queue command_queue, + NativeKernel user_func, + void* args, + IntPtr cb_args, + cl_uint num_mem_objects, + [In] cl_mem[] mem_list, + [Out] [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] IntPtr[] args_mem_loc, + cl_uint num_events_in_wait_list, + [In]cl_event[] event_wait_list, + cl_event* _event); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueMarker(cl_command_queue command_queue, cl_event* _event); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueWaitForEvents(cl_command_queue command_queue, + cl_uint num_events, + [In] [MarshalAs(UnmanagedType.LPArray)] cl_event[] _event_list); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueBarrier(cl_command_queue command_queue); + + #endregion + + #region Flush and Finish API + + [DllImport(Configuration.Library)] + public extern static ErrorCode clFlush(cl_command_queue command_queue); + [DllImport(Configuration.Library)] + public extern static ErrorCode clFinish(cl_command_queue command_queue); + + #endregion + + #region Event Object API + + [DllImport(Configuration.Library)] + public extern static ErrorCode clWaitForEvents(cl_uint num_events, + [In] [MarshalAs(UnmanagedType.LPArray)] cl_event[] _event_list); + [DllImport(Configuration.Library)] + public extern static ErrorCode clGetEventInfo(cl_event _event, + cl_event_info param_name, + IntPtr param_value_size, + void* param_value, + out IntPtr param_value_size_ret); + [DllImport(Configuration.Library)] + public extern static ErrorCode clRetainEvent(cl_event _event); + [DllImport(Configuration.Library)] + public extern static ErrorCode clReleaseEvent(cl_event _event); + + #endregion + + #region Sampler API + + // Sampler APIs + [DllImport(Configuration.Library)] + public extern static cl_sampler clCreateSampler(cl_context context, cl_bool normalized_coords, cl_addressing_mode addressing_mode, cl_filter_mode filter_mode, out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static ErrorCode clRetainSampler(cl_sampler sampler); + [DllImport(Configuration.Library)] + public extern static ErrorCode clReleaseSampler(cl_sampler sampler); + [DllImport(Configuration.Library)] + public extern static ErrorCode clGetSamplerInfo(cl_sampler sampler, cl_sampler_info param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret); + + #endregion + + #region GLObject API + + [DllImport(Configuration.Library)] + public extern static cl_mem clCreateFromGLBuffer(cl_context context, + cl_mem_flags flags, + GLuint bufobj, + out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static cl_mem clCreateFromGLTexture2D(cl_context context, + cl_mem_flags flags, + GLenum target, + GLint mipLevel, + GLuint texture, + out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static cl_mem clCreateFromGLTexture3D(cl_context context, + cl_mem_flags flags, + GLenum target, + GLint mipLevel, + GLuint texture, + out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static cl_mem clCreateFromGLRenderbuffer(cl_context context, + cl_mem_flags flags, + GLuint renderBuffer, + out ErrorCode errcode_ret); + [DllImport(Configuration.Library)] + public extern static ErrorCode clGetGLObjectInfo(cl_mem memobj, + out cl_gl_object_type gl_object_type, + out GLuint gl_object_name); + [DllImport(Configuration.Library)] + public extern static ErrorCode clGetGLTextureInfo(cl_mem memobj, + cl_gl_texture_info param_name, + IntPtr param_value_size, + void* param_value, + out IntPtr param_value_size_ret); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueAcquireGLObjects(cl_command_queue command_queue, + cl_uint num_objects, + [In] cl_mem[] mem_objects, + cl_uint num_events_in_wait_list, + [In] cl_event[] event_wait_list, + cl_event* _event); + [DllImport(Configuration.Library)] + public extern static ErrorCode clEnqueueReleaseGLObjects(cl_command_queue command_queue, + cl_uint num_objects, + [In] cl_mem[] mem_objects, + cl_uint num_events_in_wait_list, + [In] cl_event[] event_wait_list, + cl_event* _event); + + #endregion + + + // Extension function access + [DllImport(Configuration.Library)] + public extern static IntPtr clGetExtensionFunctionAddress(string func_name); + + [DllImport(Configuration.Library)] + public extern static cl_int clGetEventProfilingInfo(cl_event _event, cl_profiling_info param_name, IntPtr param_value_size, void* param_value, out IntPtr param_value_size_ret); + } + +} diff --git a/OpenCLNet/OpenCLManager.Designer.cs b/OpenCLNet/OpenCLManager.Designer.cs new file mode 100644 index 0000000..c22ff45 --- /dev/null +++ b/OpenCLNet/OpenCLManager.Designer.cs @@ -0,0 +1,36 @@ +namespace OpenCLNet +{ + partial class OpenCLManager + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + } + + #endregion + } +} diff --git a/OpenCLNet/OpenCLManager.cs b/OpenCLNet/OpenCLManager.cs new file mode 100644 index 0000000..e4fe6f7 --- /dev/null +++ b/OpenCLNet/OpenCLManager.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Text; + +namespace OpenCLNet +{ + public partial class OpenCLManager : Component + { + public List RequireExtensions = new List(); + public bool RequireImageSupport { get; set; } + public bool UseMultiplePlatforms { get; set; } + public List DeviceTypes = new List(); + + public OpenCLManager() + { + InitializeComponent(); + } + + public OpenCLManager(IContainer container) + { + container.Add(this); + + InitializeComponent(); + } + + public void InitializeOpenCL() + { + if (OpenCL.NumberOfPlatforms == 0) + return; + + foreach (Platform p in OpenCL.GetPlatforms()) + { + //p.QueryDevices(DeviceType DeviceType. + } + } + } +} diff --git a/OpenCLNet/OpenCLNet.csproj b/OpenCLNet/OpenCLNet.csproj new file mode 100644 index 0000000..5eda44c --- /dev/null +++ b/OpenCLNet/OpenCLNet.csproj @@ -0,0 +1,162 @@ + + + + Debug + AnyCPU + 9.0.21022 + 2.0 + {758285C6-1ACA-458A-9906-EE6701D5AF87} + Library + Properties + OpenCLNet + OpenCLNet + v3.5 + 512 + + + 3.5 + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + true + AllRules.ruleset + + + true + bin\x64\Debug\ + DEBUG;TRACE + true + full + x64 + prompt + AllRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + true + AllRules.ruleset + + + true + bin\x86\Debug\ + DEBUG;TRACE + true + full + x86 + prompt + AllRules.ruleset + + + bin\x86\Release\ + TRACE + true + pdbonly + x86 + prompt + true + AllRules.ruleset + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + + + + + + + + + + + + Component + + + OpenCLManager.cs + + + + + + + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + true + + + False + Windows Installer 3.1 + true + + + + + \ No newline at end of file diff --git a/OpenCLNet/OpenCLNet.csproj.user b/OpenCLNet/OpenCLNet.csproj.user new file mode 100644 index 0000000..6f3ee55 --- /dev/null +++ b/OpenCLNet/OpenCLNet.csproj.user @@ -0,0 +1,19 @@ + + + + true + + + true + + + + + + + + + en-US + false + + \ No newline at end of file diff --git a/OpenCLNet/Platform.cs b/OpenCLNet/Platform.cs new file mode 100644 index 0000000..0221eb3 --- /dev/null +++ b/OpenCLNet/Platform.cs @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Text; + +namespace OpenCLNet +{ + + unsafe public class Platform : InteropTools.IPropertyContainer + { + public IntPtr PlatformID { get; protected set; } + public string Profile { get { return InteropTools.ReadString( this, (uint)PlatformInfo.PROFILE ); } } + public string Version { get { return InteropTools.ReadString( this, (uint)PlatformInfo.VERSION ); } } + public string Name { get { return InteropTools.ReadString( this, (uint)PlatformInfo.NAME ); } } + public string Vendor { get { return InteropTools.ReadString( this, (uint)PlatformInfo.VENDOR ); } } + public string Extensions { get { return InteropTools.ReadString( this, (uint)PlatformInfo.EXTENSIONS ); } } + + protected Dictionary _Devices = new Dictionary(); + Device[] DeviceList; + IntPtr[] DeviceIDs; + + protected HashSet ExtensionHashSet = new HashSet(); + + public Platform( IntPtr platformID ) + { + PlatformID = platformID; + + // Create a local representation of all devices + DeviceIDs = QueryDeviceIntPtr( DeviceType.ALL ); + for( int i=0; i + /// Wrapper for an OpenCL Program + /// + unsafe public class Program : IDisposable, InteropTools.IPropertyContainer + { + // Track whether Dispose has been called. + private bool disposed = false; + + #region Properties + + public Context Context { get; protected set; } + public IntPtr ProgramID { get; protected set; } + public string Source { get { return InteropTools.ReadString( this, (uint)ProgramInfo.SOURCE ); } } + public uint ReferenceCount { get { return InteropTools.ReadUInt( this, (uint)ProgramInfo.REFERENCE_COUNT ); } } + public uint NumDevices { get { return InteropTools.ReadUInt( this, (uint)ProgramInfo.NUM_DEVICES ); } } + + public Device[] Devices + { + get + { + uint numDevices = NumDevices; + if( numDevices==0 ) + return null; + + byte[] data = InteropTools.ReadBytes( this, (uint)ProgramInfo.DEVICES ); + IntPtr[] deviceIDs = new IntPtr[numDevices]; + fixed( byte* pData = data ) + { + void** pBS = (void**)pData; + for( int i=0; i CreateKernelDictionary() + { + Kernel[] kernels = CreateKernels(); + Dictionary kernelDictionary = new Dictionary(); + + foreach (Kernel k in kernels) + kernelDictionary[k.FunctionName] = k; + + return kernelDictionary; + } + + public static implicit operator IntPtr( Program p ) + { + return p.ProgramID; + } + + + public string GetBuildOptions( Device device ) + { + BuildInfo buildInfo; + + buildInfo = new BuildInfo( this, device ); + return InteropTools.ReadString( buildInfo, (uint)ProgramBuildInfo.OPTIONS ); + } + + public string GetBuildLog( Device device ) + { + BuildInfo buildInfo; + + buildInfo = new BuildInfo( this, device ); + return InteropTools.ReadString( buildInfo, (uint)ProgramBuildInfo.LOG ); + } + + public BuildStatus GetBuildStatus( Device device ) + { + BuildInfo buildInfo; + + buildInfo = new BuildInfo( this, device ); + return (BuildStatus)InteropTools.ReadInt( buildInfo, (uint)ProgramBuildInfo.STATUS ); + } + + class BuildInfo : InteropTools.IPropertyContainer + { + Program Program; + Device Device; + + public BuildInfo( Program p, Device d ) + { + Program = p; + Device = d; + } + + #region IPropertyContainer Members + + public IntPtr GetPropertySize( uint key ) + { + ErrorCode result; + IntPtr size; + + result = (ErrorCode)OpenCL.GetProgramBuildInfo( Program.ProgramID, Device.DeviceID, key, IntPtr.Zero, null, out size ); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "clGetProgramBuildInfo failed with error code "+result, result); + + return size; + } + + public void ReadProperty( uint key, IntPtr keyLength, void* pBuffer ) + { + ErrorCode result; + IntPtr size; + + result = (ErrorCode)OpenCL.GetProgramBuildInfo( Program.ProgramID, Device.DeviceID, key, keyLength, pBuffer, out size ); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "clGetProgramBuildInfo failed with error code "+result, result); + } + + #endregion + } + + #region IPropertyContainer Members + + public IntPtr GetPropertySize( uint key ) + { + ErrorCode result; + IntPtr size; + + result = (ErrorCode)OpenCL.GetProgramInfo( ProgramID, key, IntPtr.Zero, null, out size ); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "clGetProgramInfo failed with error code "+result, result); + + return size; + } + + public void ReadProperty( uint key, IntPtr keyLength, void* pBuffer ) + { + ErrorCode result; + IntPtr size; + + result = (ErrorCode)OpenCL.GetProgramInfo( ProgramID, key, keyLength, pBuffer, out size ); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "clGetProgramInfo failed with error code "+result, result); + } + + #endregion + } +} diff --git a/OpenCLNet/Properties/AssemblyInfo.cs b/OpenCLNet/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c8a894d --- /dev/null +++ b/OpenCLNet/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenCLNet")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("OpenCLNet")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2009")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("c5dc037e-4b59-408c-b17e-2757fa1fab10")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenCLNet/Sampler.cs b/OpenCLNet/Sampler.cs new file mode 100644 index 0000000..828d0f7 --- /dev/null +++ b/OpenCLNet/Sampler.cs @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OpenCLNet +{ + + /// + /// Wrapper for an OpenCL sampler + /// + unsafe public class Sampler : IDisposable, InteropTools.IPropertyContainer + { + // Track whether Dispose has been called. + private bool disposed = false; + + #region Properties + + public IntPtr SamplerID { get; protected set; } + public Context Context { get; protected set; } + + public uint ReferenceCount { get { return InteropTools.ReadUInt( this, (uint)SamplerInfo.REFERENCE_COUNT ); } } + public AddressingMode AddressingMode { get { return (AddressingMode)InteropTools.ReadUInt( this, (uint)SamplerInfo.ADDRESSING_MODE ); } } + public FilterMode FilterMode { get { return (FilterMode)InteropTools.ReadUInt( this, (uint)SamplerInfo.FILTER_MODE ); } } + public bool NormalizedCoords { get { return InteropTools.ReadBool( this, (uint)SamplerInfo.NORMALIZED_COORDS ); } } + + #endregion + + #region Construction / Destruction + + internal Sampler( Context context, IntPtr samplerID ) + { + Context = context; + SamplerID = samplerID; + } + + // Use C# destructor syntax for finalization code. + // This destructor will run only if the Dispose method + // does not get called. + // It gives your base class the opportunity to finalize. + // Do not provide destructors in types derived from this class. + ~Sampler() + { + // Do not re-create Dispose clean-up code here. + // Calling Dispose(false) is optimal in terms of + // readability and maintainability. + Dispose( false ); + } + + #endregion + + #region IDisposable Members + + // Implement IDisposable. + // Do not make this method virtual. + // A derived class should not be able to override this method. + public void Dispose() + { + Dispose( true ); + // This object will be cleaned up by the Dispose method. + // Therefore, you should call GC.SupressFinalize to + // take this object off the finalization queue + // and prevent finalization code for this object + // from executing a second time. + GC.SuppressFinalize( this ); + } + + // Dispose(bool disposing) executes in two distinct scenarios. + // If disposing equals true, the method has been called directly + // or indirectly by a user's code. Managed and unmanaged resources + // can be disposed. + // If disposing equals false, the method has been called by the + // runtime from inside the finalizer and you should not reference + // other objects. Only unmanaged resources can be disposed. + private void Dispose( bool disposing ) + { + // Check to see if Dispose has already been called. + if( !this.disposed ) + { + // If disposing equals true, dispose all managed + // and unmanaged resources. + if( disposing ) + { + // Dispose managed resources. + } + + // Call the appropriate methods to clean up + // unmanaged resources here. + // If disposing is false, + // only the following code is executed. + OpenCL.ReleaseSampler( SamplerID ); + SamplerID = IntPtr.Zero; + + // Note disposing has been done. + disposed = true; + } + } + + #endregion + + #region IPropertyContainer Members + + + public IntPtr GetPropertySize( uint key ) + { + ErrorCode result; + IntPtr size; + + result = (ErrorCode)OpenCL.GetSamplerInfo( SamplerID, key, IntPtr.Zero, null, out size ); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "clGetSamplerInfo failed with error code "+result, result); + + return size; + } + + public void ReadProperty( uint key, IntPtr keyLength, void* pBuffer ) + { + ErrorCode result; + IntPtr size; + + result = (ErrorCode)OpenCL.GetSamplerInfo( SamplerID, key, keyLength, pBuffer, out size ); + if( result!=ErrorCode.SUCCESS ) + throw new OpenCLException( "clGetSamplerInfo failed with error code "+result, result); + } + + + #endregion + } +} diff --git a/OpenCLNet/SimpleOCLHelper.cs b/OpenCLNet/SimpleOCLHelper.cs new file mode 100644 index 0000000..d48d82b --- /dev/null +++ b/OpenCLNet/SimpleOCLHelper.cs @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace OpenCLNet +{ + public class SimpleOCLHelper + { + public Platform Platform; + /// + /// The devices bound to the Helper + /// + public Device[] Devices; + /// + /// The Context associated with this Helper + /// + public Context Context; + /// + /// CommandQueue for device with same index + /// + public CommandQueue[] CQs; + /// + /// Alias for CQs[0] + /// + public CommandQueue CQ; + protected Program Program; + protected Dictionary Kernels; + + public SimpleOCLHelper(Platform platform, DeviceType deviceType, string source) + { + Platform = platform; + Initialize(deviceType, source); + } + + protected virtual void Initialize(DeviceType deviceType, string source) + { + Devices = Platform.QueryDevices(deviceType); + if (Devices.Length == 0) + throw new OpenCLException("No devices of type "+deviceType+" present"); + + Context = Platform.CreateContext(null,Devices,null, IntPtr.Zero); + CQs = new CommandQueue[Devices.Length]; + for( int i=0; i + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.menuStrip1 = new System.Windows.Forms.MenuStrip(); + this.testToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.startToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.listBoxOutput = new System.Windows.Forms.ListBox(); + this.groupBox2 = new System.Windows.Forms.GroupBox(); + this.listBoxWarnings = new System.Windows.Forms.ListBox(); + this.groupBox3 = new System.Windows.Forms.GroupBox(); + this.listBoxErrors = new System.Windows.Forms.ListBox(); + this.menuStrip1.SuspendLayout(); + this.groupBox1.SuspendLayout(); + this.groupBox2.SuspendLayout(); + this.groupBox3.SuspendLayout(); + this.SuspendLayout(); + // + // menuStrip1 + // + this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.testToolStripMenuItem}); + this.menuStrip1.Location = new System.Drawing.Point(0, 0); + this.menuStrip1.Name = "menuStrip1"; + this.menuStrip1.Size = new System.Drawing.Size(685, 24); + this.menuStrip1.TabIndex = 0; + this.menuStrip1.Text = "menuStrip"; + // + // testToolStripMenuItem + // + this.testToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.startToolStripMenuItem}); + this.testToolStripMenuItem.Name = "testToolStripMenuItem"; + this.testToolStripMenuItem.Size = new System.Drawing.Size(41, 20); + this.testToolStripMenuItem.Text = "&Test"; + // + // startToolStripMenuItem + // + this.startToolStripMenuItem.Name = "startToolStripMenuItem"; + this.startToolStripMenuItem.Size = new System.Drawing.Size(98, 22); + this.startToolStripMenuItem.Text = "&Start"; + this.startToolStripMenuItem.Click += new System.EventHandler(this.startToolStripMenuItem_Click); + // + // groupBox1 + // + this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.groupBox1.Controls.Add(this.listBoxOutput); + this.groupBox1.Location = new System.Drawing.Point(0, 27); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Size = new System.Drawing.Size(685, 269); + this.groupBox1.TabIndex = 4; + this.groupBox1.TabStop = false; + this.groupBox1.Text = "Output"; + // + // listBoxOutput + // + this.listBoxOutput.Dock = System.Windows.Forms.DockStyle.Fill; + this.listBoxOutput.FormattingEnabled = true; + this.listBoxOutput.IntegralHeight = false; + this.listBoxOutput.Location = new System.Drawing.Point(3, 16); + this.listBoxOutput.Name = "listBoxOutput"; + this.listBoxOutput.Size = new System.Drawing.Size(679, 250); + this.listBoxOutput.TabIndex = 2; + // + // groupBox2 + // + this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.groupBox2.Controls.Add(this.listBoxWarnings); + this.groupBox2.Location = new System.Drawing.Point(0, 302); + this.groupBox2.Name = "groupBox2"; + this.groupBox2.Size = new System.Drawing.Size(685, 121); + this.groupBox2.TabIndex = 5; + this.groupBox2.TabStop = false; + this.groupBox2.Text = "Warnings"; + // + // listBoxWarnings + // + this.listBoxWarnings.Dock = System.Windows.Forms.DockStyle.Fill; + this.listBoxWarnings.FormattingEnabled = true; + this.listBoxWarnings.IntegralHeight = false; + this.listBoxWarnings.Location = new System.Drawing.Point(3, 16); + this.listBoxWarnings.Name = "listBoxWarnings"; + this.listBoxWarnings.Size = new System.Drawing.Size(679, 102); + this.listBoxWarnings.TabIndex = 3; + // + // groupBox3 + // + this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.groupBox3.Controls.Add(this.listBoxErrors); + this.groupBox3.Location = new System.Drawing.Point(0, 426); + this.groupBox3.Name = "groupBox3"; + this.groupBox3.Size = new System.Drawing.Size(685, 111); + this.groupBox3.TabIndex = 6; + this.groupBox3.TabStop = false; + this.groupBox3.Text = "Errors"; + // + // listBoxErrors + // + this.listBoxErrors.Dock = System.Windows.Forms.DockStyle.Fill; + this.listBoxErrors.FormattingEnabled = true; + this.listBoxErrors.IntegralHeight = false; + this.listBoxErrors.Location = new System.Drawing.Point(3, 16); + this.listBoxErrors.Name = "listBoxErrors"; + this.listBoxErrors.Size = new System.Drawing.Size(679, 92); + this.listBoxErrors.TabIndex = 4; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(685, 537); + this.Controls.Add(this.groupBox3); + this.Controls.Add(this.groupBox2); + this.Controls.Add(this.groupBox1); + this.Controls.Add(this.menuStrip1); + this.MainMenuStrip = this.menuStrip1; + this.Name = "Form1"; + this.Text = "Form1"; + this.menuStrip1.ResumeLayout(false); + this.menuStrip1.PerformLayout(); + this.groupBox1.ResumeLayout(false); + this.groupBox2.ResumeLayout(false); + this.groupBox3.ResumeLayout(false); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.MenuStrip menuStrip1; + private System.Windows.Forms.ToolStripMenuItem testToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem startToolStripMenuItem; + private System.Windows.Forms.GroupBox groupBox1; + private System.Windows.Forms.ListBox listBoxOutput; + private System.Windows.Forms.GroupBox groupBox2; + private System.Windows.Forms.GroupBox groupBox3; + private System.Windows.Forms.ListBox listBoxWarnings; + private System.Windows.Forms.ListBox listBoxErrors; + } +} + diff --git a/UnitTests/Form1.cs b/UnitTests/Form1.cs new file mode 100644 index 0000000..8e510c0 --- /dev/null +++ b/UnitTests/Form1.cs @@ -0,0 +1,555 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Windows.Forms; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; +using OpenCLNet; + +namespace UnitTests +{ + public partial class Form1 : Form + { + Platform[] Platforms; + Regex ParseOpenCLVersion = new Regex(@"OpenCL (?\d+)\.(?\d+).*"); + + public Form1() + { + InitializeComponent(); + } + + private void startToolStripMenuItem_Click(object sender, EventArgs e) + { + try + { + listBoxErrors.Items.Clear(); + listBoxWarnings.Items.Clear(); + listBoxOutput.Items.Clear(); + RunTests(); + } + catch (Exception ex) + { + MessageBox.Show(ex.ToString(), "Test terminated with a fatal exception."); + } + } + + private void RunTests() + { + TestOpenCLClass(); + } + + private void TestOpenCLClass() + { + if (OpenCL.NumberOfPlatforms <= 0) + { + listBoxOutput.Items.Add("OpenCL.NumberOfPlatforms=" + OpenCL.NumberOfPlatforms); + throw new Exception("TestOpenCLClass: NumberOfPlatforms<0. Is the API available at all?"); + } + + Platforms = OpenCL.GetPlatforms(); + if (Platforms.Length != OpenCL.NumberOfPlatforms) + Error("OpenCL.NumberOfPlatforms!=Length of openCL.GetPlatforms()" + OpenCL.NumberOfPlatforms); + + for (int platformIndex = 0; platformIndex < Platforms.Length; platformIndex++) + { + if (OpenCL.GetPlatform(platformIndex) != Platforms[platformIndex]) + Error("openCL.GetPlatform(platformIndex)!=Platforms[platformIndex]"); + + Output("Testing Platform " + platformIndex); + TestPlatform(Platforms[platformIndex]); + } + } + + private void TestPlatform(Platform p) + { + Device[] allDevices; + Device[] cpuDevices; + Device[] gpuDevices; + Device[] acceleratorDevices; + + Output("Name: " + p.Name); + Output("Vendor:" + p.Vendor); + Output("Version:" + p.Version); + + // Check format of version string + Match m = ParseOpenCLVersion.Match(p.Version); + if (!m.Success) + Warning("Platform " + p.Name + " has an invalid version string"); + else + { + if (m.Groups["MajorVersion"].Value != "1" && m.Groups["MinorVersion"].Value != "0") + Warning("Platform " + p.Name + " has a version number!=1.0(Not really a problem, but this test is written for 1.0)"); + } + + // Check format of profile + Output("Profile:" + p.Profile); + if (p.Profile == "FULL_PROFILE" || p.Profile == "EMBEDDED_PROFILE") + Output("Profile:" + p.Profile); + else + Warning("Platform " + p.Name + " has unknown profile "+p.Profile); + + Output("Extensions: " + p.Extensions); + + // Test whether number of devices is consistent + allDevices = p.QueryDevices(DeviceType.ALL); + if( allDevices.Length<=0 ) + Warning( "Platform "+p.Name+" has no devices" ); + + cpuDevices = p.QueryDevices(DeviceType.CPU); + gpuDevices = p.QueryDevices(DeviceType.GPU); + acceleratorDevices = p.QueryDevices(DeviceType.ACCELERATOR); + if( allDevices.Length!=cpuDevices.Length+gpuDevices.Length+acceleratorDevices.Length ) + Warning( "QueryDevices( DeviceType.ALL ) return length inconsistent with sum of special purpose queries" ); + + // Create a few contexts and test them + Output( "Testing Platform.CreateDefaultContext()" ); + using (Context c = p.CreateDefaultContext()) + { + Output("Testing context"+c); + TestContext(c); + } + Output(""); + Output(""); + + if (cpuDevices.Length > 0) + { + Output("Testing Platform.CreateContext()"); + using (Context c = p.CreateContext(null, cpuDevices, new ContextNotify(ContextNotifyFunc), (IntPtr)0x01234567)) + { + Output("Testing context" + c); + TestContext(c); + } + Output(""); + Output(""); + } + + if (gpuDevices.Length > 0) + { + Output("Testing Platform.CreateContext()"); + using (Context c = p.CreateContext(null, gpuDevices, new ContextNotify(ContextNotifyFunc), (IntPtr)0x01234567)) + { + Output("Testing context" + c); + TestContext(c); + } + Output(""); + Output(""); + } + + if (cpuDevices.Length > 0) + { + Output("Testing Platform.CreateContextFromType()"); + IntPtr[] contextProperties = new IntPtr[] + { + (IntPtr)ContextProperties.PLATFORM, p.PlatformID, + IntPtr.Zero + }; + using (Context c = p.CreateContextFromType(contextProperties, DeviceType.CPU, new ContextNotify(ContextNotifyFunc), (IntPtr)0x01234567)) + { + Output("Testing context" + c); + TestContext(c); + } + } + + if (gpuDevices.Length > 0) + { + Output("Testing Platform.CreateContextFromType()"); + IntPtr[] contextProperties = new IntPtr[] + { + (IntPtr)ContextProperties.PLATFORM, p.PlatformID, + IntPtr.Zero + }; + using (Context c = p.CreateContextFromType(contextProperties, DeviceType.GPU, new ContextNotify(ContextNotifyFunc), (IntPtr)0x01234567)) + { + Output("Testing context" + c); + TestContext(c); + } + } + } + + private void ContextNotifyFunc( string errInfo, byte[] privateInfo, IntPtr cb, IntPtr userData ) + { + Error(errInfo); + } + + int NativeKernelCalled = 0; + NativeKernel NativeKernelCallRef; + + private void TestContext(Context c) + { + Device[] devices = c.Devices; + OpenCLNet.Program p = c.CreateProgramFromFile("MemoryTests.cl"); + Dictionary kernelDictionary; + + try + { + p.Build(); + } + catch (OpenCLException ocle) + { + throw ocle; + } + kernelDictionary = p.CreateKernelDictionary(); + NativeKernelCallRef = new NativeKernel(NativeKernelTest); + for (int deviceIndex = 0; deviceIndex < devices.Length; deviceIndex++) + { + Device d; + + d = devices[deviceIndex]; + using (CommandQueue cq = c.CreateCommandQueue(d)) + { + if ( (d.ExecutionCapabilities & (ulong)DeviceExecCapabilities.NATIVE_KERNEL)!=0 ) + { + Output("Testing native kernel execution"); + cq.EnqueueNativeKernel(NativeKernelCallRef); + cq.EnqueueBarrier(); + if (NativeKernelCalled != 1) + Error("EnqueueNativeKernel failed"); + Interlocked.Decrement(ref NativeKernelCalled); + } + else + { + Output("Testing native kernel execution: Not supported"); + } + + TestMem(c, cq, kernelDictionary); + TestDevice(d); + TestCommandQueue(c, cq); + TestKernel(c, cq, kernelDictionary["ArgIO"]); + } + } + } + + public unsafe void NativeKernelTest(IntPtr args) + { + Interlocked.Increment(ref NativeKernelCalled); + } + + [StructLayout(LayoutKind.Sequential, Pack=1)] + internal struct IOKernelArgs + { + internal long outLong; + internal int outInt; + internal float outSingle; + internal IntPtr outIntPtr; + } + + private unsafe void TestKernel(Context c, CommandQueue cq, Kernel argIOKernel) + { + Mem outArgBuffer = c.CreateBuffer(MemFlags.WRITE_ONLY, sizeof(IOKernelArgs), IntPtr.Zero); + + Output("Testing kernel - Argument return"); + + argIOKernel.SetIntArg(0, 1); + argIOKernel.SetLongArg(1, 65); + argIOKernel.SetSingleArg(2, 38.4f); + argIOKernel.SetIntPtrArg(3, new IntPtr(0x01234567)); + argIOKernel.SetIntPtrArg(4, outArgBuffer.MemID); + + cq.EnqueueTask(argIOKernel); + + IntPtr outArgPtr = cq.EnqueueMapBuffer( outArgBuffer, true, MapFlags.READ, IntPtr.Zero, (IntPtr)sizeof(IOKernelArgs) ); + IOKernelArgs args = (IOKernelArgs)Marshal.PtrToStructure(outArgPtr, typeof(IOKernelArgs)); + cq.EnqueueUnmapMemObject(outArgBuffer, outArgPtr); + + if (args.outInt != 1) + Error("argIOKernel failed to return correct arguments"); + if (args.outLong != 65) + Error("argIOKernel failed to return correct arguments"); + if (args.outSingle != 38.4f) + Error("argIOKernel failed to return correct arguments"); + if (args.outIntPtr != new IntPtr(0x01234567)) + Error("argIOKernel failed to return correct arguments"); + } + + private void TestMem(Context c, CommandQueue cq, Dictionary kernelDictionary ) + { + long size = 8192; + + Output( "Testing Mem class" ); + Output( "Allocating "+size+" bytes of READ_WRITE memory" ); + using (Mem buffer = c.CreateBuffer(MemFlags.READ_WRITE, size, IntPtr.Zero)) + { + Output("Mem.MemSize=" + size); + if (buffer.MemSize.ToInt64() != size) + Error("Mem.Size!=input size"); + Output("Mem.MemType=" + buffer.MemType); + if (buffer.MemType != MemObjectType.BUFFER) + Error("Mem.MemType!=MemObjectType.BUFFER"); + + Output("Mem.MapCount=" + buffer.MapCount); + if (buffer.MapCount != 0) + Error("Mem.MapCount!=0"); + + Kernel k = kernelDictionary["TestReadWriteMemory"]; + k.SetArg(0, buffer); + k.SetArg(1, (IntPtr)size); + cq.EnqueueTask(k); + cq.EnqueueBarrier(); + } + + Output("Allocating " + size + " bytes of READ memory"); + using (Mem buffer = c.CreateBuffer(MemFlags.READ_ONLY, size, IntPtr.Zero)) + { + Output("Mem.MemSize=" + size); + if (buffer.MemSize.ToInt64() != size) + Error("Mem.Size!=input size"); + Output("Mem.MemType=" + buffer.MemType); + if (buffer.MemType != MemObjectType.BUFFER) + Error("Mem.MemType!=MemObjectType.BUFFER"); + + Output("Mem.MapCount=" + buffer.MapCount); + if (buffer.MapCount != 0) + Error("Mem.MapCount!=0"); + + Kernel k = kernelDictionary["TestReadMemory"]; + k.SetArg(0, buffer); + k.SetArg(1, (IntPtr)size); + cq.EnqueueTask(k); + cq.EnqueueBarrier(); + } + + Output("Allocating " + size + " bytes of WRITE memory"); + using (Mem buffer = c.CreateBuffer(MemFlags.WRITE_ONLY, size, IntPtr.Zero)) + { + Output("Mem.MemSize=" + size); + if (buffer.MemSize.ToInt64() != size) + Error("Mem.Size!=input size"); + Output("Mem.MemType=" + buffer.MemType); + if (buffer.MemType != MemObjectType.BUFFER) + Error("Mem.MemType!=MemObjectType.BUFFER"); + + Output("Mem.MapCount=" + buffer.MapCount); + if (buffer.MapCount != 0) + Error("Mem.MapCount!=0"); + + Kernel k = kernelDictionary["TestWriteMemory"]; + k.SetArg(0, buffer); + k.SetArg(1, (IntPtr)size); + cq.EnqueueTask(k); + cq.EnqueueBarrier(); + } + } + + private void TestDevice( Device d ) + { + Output("Testing device: " + d.Name); + // d.ToString() is overloaded to output all properties as a string, so every property will be used that way + Output(d.ToString()); + } + + private void TestCommandQueue(Context c, CommandQueue cq ) + { + string programName = @"MemoryTests.cl"; + + Output("Testing compilation of: " + programName); + OpenCLNet.Program p0 = c.CreateProgramWithSource(File.ReadAllLines(programName)); + OpenCLNet.Program p = c.CreateProgramWithSource(File.ReadAllText(programName)); + p0.Build(); + p.Build(); + Kernel k = p.CreateKernel(@"LoopAndDoNothing"); + + TestCommandQueueMemCopy(c, cq); + TestCommandQueueAsync(c, cq, k ); + } + + #region TestCommandQueue helper functions + + private void TestCommandQueueAsync(Context c, CommandQueue cq, Kernel kernel ) + { + List events = new List(); + Event clEvent; + + Output("Testing asynchronous task issuing (clEnqueueTask) and waiting for events"); + + // Issue a bunch of slow operations + kernel.SetArg(0, 5000000); + for (int i = 0; i < 10; i++) + { + cq.EnqueueTask(kernel, 0, null, out clEvent); + events.Add(clEvent); + } + + // Issue a bunch of fast operations + kernel.SetArg(0, 500); + for (int i = 0; i < 1000; i++) + { + cq.EnqueueTask(kernel, 0, null, out clEvent); + events.Add(clEvent); + } + + Event[] eventList = events.ToArray(); + cq.EnqueueWaitForEvents(eventList.Length, eventList); + while (events.Count > 0) + { + events[0].Dispose(); + events.RemoveAt(0); + } + } + + private void TestCommandQueueMemCopy(Context c, CommandQueue cq) + { + AlignedArrayFloat aafSrc = new AlignedArrayFloat(1024 * 1024, 64); + AlignedArrayFloat aafDst = new AlignedArrayFloat(1024 * 1024, 64); + + SetAAF(aafSrc, 0.0f); + SetAAF(aafDst, 1.0f); + + /// Test HOST_PTR -> HOST_PTR copy + /// The call to EnqueueMapBuffer synchronizes caches before testing the result + Output("Testing synchronous host memory->memory copy(clEnqueueCopyBuffer)"); + using (Mem memSrc = c.CreateBuffer(MemFlags.USE_HOST_PTR, aafSrc.ByteLength, aafSrc)) + { + using (Mem memDst = c.CreateBuffer(MemFlags.USE_HOST_PTR, aafDst.ByteLength, aafDst)) + { + cq.EnqueueCopyBuffer(memSrc, memDst, IntPtr.Zero, IntPtr.Zero, (IntPtr)aafSrc.ByteLength); + cq.EnqueueBarrier(); + IntPtr mappedPtr = cq.EnqueueMapBuffer(memDst, true, MapFlags.READ, (IntPtr)0, (IntPtr)aafDst.ByteLength); + if (!TestAAF(aafDst, 0.0f)) + Error("EnqueueCopyBuffer failed, destination is invalid"); + cq.EnqueueUnmapMemObject(memDst, mappedPtr); + cq.EnqueueBarrier(); + } + } + + /// Test COPY_HOST_PTR -> COPY_HOST_PTR copy + /// Verify that original source buffers are intact and that the copy was successful + Output("Testing synchronous host memory->memory copy(clEnqueueCopyBuffer)"); + SetAAF(aafSrc, 0.0f); + SetAAF(aafDst, 1.0f); + using (Mem memSrc = c.CreateBuffer(MemFlags.COPY_HOST_PTR, aafSrc.ByteLength, aafSrc)) + { + using (Mem memDst = c.CreateBuffer(MemFlags.COPY_HOST_PTR, aafSrc.ByteLength, aafDst)) + { + SetAAF(aafSrc, 2.0f); + SetAAF(aafDst, 3.0f); + + cq.EnqueueCopyBuffer(memSrc, memDst, IntPtr.Zero, IntPtr.Zero, (IntPtr)aafSrc.ByteLength); + cq.Finish(); + + if (!TestAAF(aafSrc, 2.0f)) + Error("Memory copy destroyed src buffer"); + if (!TestAAF(aafDst, 3.0f)) + Error("Memory copy destroyed dst buffer"); + + cq.EnqueueReadBuffer(memDst, true, IntPtr.Zero, (IntPtr)aafDst.ByteLength, aafDst); + cq.Finish(); + if (!TestAAF(aafDst, 0.0f)) + Error("Memory copy failed"); + } + } + + /// Test ALLOC_HOST_PTR -> ALLOC_HOST_PTR copy + Output("Testing synchronous host memory->memory copy(clEnqueueCopyBuffer)"); + SetAAF(aafSrc, 0.0f); + SetAAF(aafDst, 1.0f); + using (Mem memSrc = c.CreateBuffer((MemFlags)((ulong)MemFlags.ALLOC_HOST_PTR + (ulong)MemFlags.READ_WRITE), aafSrc.ByteLength, IntPtr.Zero)) + { + using (Mem memDst = c.CreateBuffer((MemFlags)((ulong)MemFlags.ALLOC_HOST_PTR + (ulong)MemFlags.WRITE_ONLY), aafSrc.ByteLength, IntPtr.Zero)) + { + cq.EnqueueWriteBuffer(memSrc, false, (IntPtr)0, (IntPtr)aafSrc.ByteLength, aafSrc); + cq.EnqueueWriteBuffer(memDst, false, (IntPtr)0, (IntPtr)aafSrc.ByteLength, aafSrc); + cq.EnqueueBarrier(); + + cq.EnqueueCopyBuffer(memSrc, memDst, IntPtr.Zero, IntPtr.Zero, (IntPtr)aafSrc.ByteLength); + cq.EnqueueBarrier(); + + cq.EnqueueReadBuffer(memDst, true, IntPtr.Zero, (IntPtr)aafDst.ByteLength, aafDst); + if (!TestAAF(aafDst, 0.0f)) + Error("Memory copy failed"); + } + } + + /// Test DEFAULT -> DEFAULT copy + Output("Testing synchronous host memory->memory copy(clEnqueueCopyBuffer)"); + SetAAF(aafSrc, 0.0f); + SetAAF(aafDst, 1.0f); + using (Mem memSrc = c.CreateBuffer((MemFlags)((ulong)MemFlags.ALLOC_HOST_PTR + (ulong)MemFlags.READ_ONLY), aafSrc.ByteLength, IntPtr.Zero)) + { + using (Mem memDst = c.CreateBuffer((MemFlags)((ulong)MemFlags.ALLOC_HOST_PTR + (ulong)MemFlags.WRITE_ONLY), aafSrc.ByteLength, IntPtr.Zero)) + { + cq.EnqueueWriteBuffer(memSrc, false, (IntPtr)0, (IntPtr)aafSrc.ByteLength, aafSrc); + cq.EnqueueWriteBuffer(memDst, false, (IntPtr)0, (IntPtr)aafSrc.ByteLength, aafSrc); + cq.EnqueueBarrier(); + + cq.EnqueueCopyBuffer(memSrc, memDst, IntPtr.Zero, IntPtr.Zero, (IntPtr)aafSrc.ByteLength); + cq.EnqueueBarrier(); + + cq.EnqueueReadBuffer(memDst, true, IntPtr.Zero, (IntPtr)aafDst.ByteLength, aafDst); + if (!TestAAF(aafDst, 0.0f)) + Error("Memory copy failed"); + } + } + } + + private bool TestAAF(AlignedArrayFloat aaf, float c) + { + for (int i = 0; i < aaf.Length; i++) + if (aaf[i] != c) + return false; + return true; + } + + private void SetAAF(AlignedArrayFloat aaf, float c) + { + for (int i = 0; i < aaf.Length; i++) + aaf[i] = c; + } + + private void SetAAFLinear(AlignedArrayFloat aaf) + { + for (int i = 0; i < aaf.Length; i++) + aaf[i] = (float)i; + } + + #endregion + + private void Output(string s) + { + listBoxOutput.Items.Add(s); + Application.DoEvents(); + } + + private void Warning(string s) + { + listBoxWarnings.Items.Add(s); + Application.DoEvents(); + } + + private void Error(string s) + { + listBoxErrors.Items.Add(s); + Application.DoEvents(); + } + } +} diff --git a/UnitTests/Form1.resx b/UnitTests/Form1.resx new file mode 100644 index 0000000..69c5649 --- /dev/null +++ b/UnitTests/Form1.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/UnitTests/Mandelbrot.cl b/UnitTests/Mandelbrot.cl new file mode 100644 index 0000000..925cf2e --- /dev/null +++ b/UnitTests/Mandelbrot.cl @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +__constant uint Palette[17][4] = +{ + { 0x00, 0x00, 0x00, 0xFF }, + { 0x00, 0xA8, 0x76, 0xFF }, + { 0x20, 0x7E, 0x62, 0xFF }, + { 0x00, 0x6D, 0x4C, 0xFF }, + { 0x35, 0xD4, 0xA4, 0xFF }, + { 0x5F, 0xD4, 0xB1, 0xFF }, + { 0x0D, 0x56, 0xA6, 0xFF }, + { 0x27, 0x4F, 0x7D, 0xFF }, + { 0x04, 0x35, 0x6C, 0xFF }, + { 0x41, 0x86, 0xD3, 0xFF }, + { 0x68, 0x9A, 0xD3, 0xFF }, + { 0x4D, 0xDE, 0x00, 0xFF }, + { 0x55, 0xA6, 0x2A, 0xFF }, + { 0x32, 0x90, 0x00, 0xFF }, + { 0x7A, 0xEE, 0x3C, 0xFF }, + { 0x99, 0xEE, 0x6B, 0xFF }, + { 0x99, 0xEE, 0x6B, 0xFF }, +/* + {0x00, 0x00, 0x5a, 0xff,}, + {0x39, 0x8c, 0xdb, 0xff,}, + {0x9b, 0xb9, 0xff, 0xff,}, + {0x4a, 0xae, 0x92, 0xff,}, + {0x4a, 0xae, 0x92, 0xff,},*/ +}; + +#define MAXITER 100 +#define PALETTELENGTH 16 + +__constant int8 i8_01234567 = (int8)( 0, 1, 2, 3, 4, 5, 6, 7 ); +__constant int8 i8_00000000 = (int8)( 0, 1, 2, 3, 4, 5, 6, 7 ); +__constant int8 i8_11111111 = (int8)( 0, 1, 2, 3, 4, 5, 6, 7 ); + +__kernel void Mandelbrot( float left, float top, float right, float bottom, int stride, __global uchar4* pOutput ) +{ + size_t width = get_global_size(0); + size_t height = get_global_size(1); + size_t cx = get_global_id(0); + size_t cy = get_global_id(1); + float dx = (right-left)/(float)width; + float dy = (bottom-top)/(float)height; + + float x0 = left+dx*(float)cx; + float y0 = top+dy*(float)cy; + float x = 0.0f; + float y = 0.0f; + int iteration = 0; + int max_iteration = MAXITER; + + while( x*x-y*y<=(2*2) && iterationoutInt = i; + pA->outLong = l; + pA->outSingle = s; + pA->outIntPtr = p; +} + +kernel void TestReadMemory( global char* pData, size_t length ) +{ + int sum; + + for( size_t i=0; i + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/UnitTests/Properties/AssemblyInfo.cs b/UnitTests/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..e718160 --- /dev/null +++ b/UnitTests/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("UnitTests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("UnitTests")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2009")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("943b1a5e-83e4-42f1-8187-a852dc5ef2a4")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/UnitTests/Properties/Resources.Designer.cs b/UnitTests/Properties/Resources.Designer.cs new file mode 100644 index 0000000..5aa51ba --- /dev/null +++ b/UnitTests/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace UnitTests.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("UnitTests.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/UnitTests/Properties/Resources.resx b/UnitTests/Properties/Resources.resx new file mode 100644 index 0000000..ffecec8 --- /dev/null +++ b/UnitTests/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/UnitTests/Properties/Settings.Designer.cs b/UnitTests/Properties/Settings.Designer.cs new file mode 100644 index 0000000..ed3a172 --- /dev/null +++ b/UnitTests/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace UnitTests.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/UnitTests/Properties/Settings.settings b/UnitTests/Properties/Settings.settings new file mode 100644 index 0000000..abf36c5 --- /dev/null +++ b/UnitTests/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/UnitTests/UnitTests.csproj b/UnitTests/UnitTests.csproj new file mode 100644 index 0000000..e2abf12 --- /dev/null +++ b/UnitTests/UnitTests.csproj @@ -0,0 +1,183 @@ + + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + true + AllRules.ruleset + + + bin\x86\Release\ + TRACE + true + pdbonly + x86 + prompt + true + AllRules.ruleset + + + true + bin\x86\Debug\ + DEBUG;TRACE + full + x86 + prompt + true + AllRules.ruleset + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + true + AllRules.ruleset + + + Debug + AnyCPU + 9.0.21022 + 2.0 + {264E13EF-4308-4033-96C1-54C13C82D7C0} + WinExe + Properties + UnitTests + UnitTests + v3.5 + 512 + + + 3.5 + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + true + AllRules.ruleset + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + + Form + + + Form1.cs + + + + + Form1.cs + Designer + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + Always + + + Always + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + {758285C6-1ACA-458A-9906-EE6701D5AF87} + OpenCLNet + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + true + + + False + Windows Installer 3.1 + true + + + + + \ No newline at end of file diff --git a/UnitTests/UnitTests.csproj.user b/UnitTests/UnitTests.csproj.user new file mode 100644 index 0000000..ce5161b --- /dev/null +++ b/UnitTests/UnitTests.csproj.user @@ -0,0 +1,25 @@ + + + + true + + + true + + + true + + + true + + + + + + + + + en-US + false + + \ No newline at end of file diff --git a/examples/ImageCrossFade/Form1.Designer.cs b/examples/ImageCrossFade/Form1.Designer.cs new file mode 100644 index 0000000..dd95624 --- /dev/null +++ b/examples/ImageCrossFade/Form1.Designer.cs @@ -0,0 +1,102 @@ +namespace ImageCrossFade +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.label1 = new System.Windows.Forms.Label(); + this.hScrollBarRatio = new System.Windows.Forms.HScrollBar(); + this.comboBoxDeviceSelector = new System.Windows.Forms.ComboBox(); + this.label2 = new System.Windows.Forms.Label(); + this.SuspendLayout(); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(12, 5); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(32, 13); + this.label1.TabIndex = 1; + this.label1.Text = "Ratio"; + // + // hScrollBarRatio + // + this.hScrollBarRatio.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.hScrollBarRatio.LargeChange = 1; + this.hScrollBarRatio.Location = new System.Drawing.Point(59, 0); + this.hScrollBarRatio.Name = "hScrollBarRatio"; + this.hScrollBarRatio.Size = new System.Drawing.Size(480, 21); + this.hScrollBarRatio.TabIndex = 2; + this.hScrollBarRatio.ValueChanged += new System.EventHandler(this.hScrollBarRatio_ValueChanged); + // + // comboBoxDeviceSelector + // + this.comboBoxDeviceSelector.FormattingEnabled = true; + this.comboBoxDeviceSelector.Location = new System.Drawing.Point(59, 24); + this.comboBoxDeviceSelector.Name = "comboBoxDeviceSelector"; + this.comboBoxDeviceSelector.Size = new System.Drawing.Size(480, 21); + this.comboBoxDeviceSelector.TabIndex = 3; + this.comboBoxDeviceSelector.SelectedIndexChanged += new System.EventHandler(this.comboBoxDeviceSelector_SelectedIndexChanged); + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(12, 27); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(41, 13); + this.label2.TabIndex = 4; + this.label2.Text = "Device"; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(548, 557); + this.Controls.Add(this.label2); + this.Controls.Add(this.comboBoxDeviceSelector); + this.Controls.Add(this.hScrollBarRatio); + this.Controls.Add(this.label1); + this.DoubleBuffered = true; + this.Name = "Form1"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label label1; + private System.Windows.Forms.HScrollBar hScrollBarRatio; + private System.Windows.Forms.ComboBox comboBoxDeviceSelector; + private System.Windows.Forms.Label label2; + } +} + diff --git a/examples/ImageCrossFade/Form1.cs b/examples/ImageCrossFade/Form1.cs new file mode 100644 index 0000000..88c5a15 --- /dev/null +++ b/examples/ImageCrossFade/Form1.cs @@ -0,0 +1,185 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Drawing.Imaging; +using System.Linq; +using System.Text; +using System.Windows.Forms; +using System.IO; +using OpenCLNet; + +namespace ImageCrossFade +{ + public partial class Form1 : Form + { + bool Initialized = false; + + Bitmap InputBitmap0; + Bitmap InputBitmap1; + BitmapData InputBitmapData0; + BitmapData InputBitmapData1; + Bitmap OutputBitmap; + + SimpleOCLHelper OCLHelper; + Mem InputBuffer0; + Mem InputBuffer1; + Kernel CrossFadeKernel; + IntPtr[] CrossFadeGlobalWorkSize = new IntPtr[2]; + + public Form1() + { + InitializeComponent(); + } + + private void Form1_Load(object sender, EventArgs e) + { + try + { + InitializeOpenCL(); + SetupBitmaps(); + Initialized = true; + } + catch (Exception ex) + { + MessageBox.Show( ex.Message, "Initiation failed..."); + Application.Exit(); + } + } + + /// + /// Loads two bitmaps and locks them for the duration of the program. + /// Also creates two OpenCL buffers that map to the locked images + /// + private void SetupBitmaps() + { + InputBitmap0 = (Bitmap)Bitmap.FromFile(@"Input0.png"); + InputBitmap1 = (Bitmap)Bitmap.FromFile(@"Input1.png"); + if (InputBitmap1.Size != InputBitmap0.Size) + InputBitmap1 = new Bitmap(InputBitmap1, InputBitmap0.Size); + OutputBitmap = new Bitmap(InputBitmap0); + + InputBitmapData0 = InputBitmap0.LockBits(new Rectangle(0, 0, InputBitmap0.Width, InputBitmap0.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + InputBitmapData1 = InputBitmap1.LockBits(new Rectangle(0, 0, InputBitmap1.Width, InputBitmap1.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + + InputBuffer0 = OCLHelper.Context.CreateBuffer(MemFlags.USE_HOST_PTR, InputBitmapData0.Stride * InputBitmapData0.Height, InputBitmapData0.Scan0); + InputBuffer1 = OCLHelper.Context.CreateBuffer(MemFlags.USE_HOST_PTR, InputBitmapData1.Stride * InputBitmapData1.Height, InputBitmapData1.Scan0); + } + + /// + /// Create a SimpleOCLHelper, using platform 0, default device type and a source containing test functions. + /// The Helper automatically compiles and creates kernels. + /// We can then extract named kernels using the GetKernel method. + /// + /// For more advanced scenarios, one might use the functions in the Platform class + /// to query devices, create contexts etc. Platforms can be enumerated using + /// for( int i=0; i + private void InitializeOpenCL() + { + if (OpenCL.NumberOfPlatforms == 0) + { + MessageBox.Show("OpenCL not available"); + Application.Exit(); + } + + string source = File.ReadAllText(@"OpenCLFunctions.cl"); + + OCLHelper = new SimpleOCLHelper(OpenCL.GetPlatform(0), DeviceType.ALL, source ); + + for (int i = 0; i < OCLHelper.Devices.Length; i++) + comboBoxDeviceSelector.Items.Add(OCLHelper.Devices[i].Vendor+":"+OCLHelper.Devices[i].Name); + comboBoxDeviceSelector.SelectedIndex = 0; + + CrossFadeKernel = OCLHelper.GetKernel("CrossFade"); + } + + /// + /// Launch the CrossFadeKernel + /// + /// First we set its arguments, + /// then we enqueue the kernel using EnqueueNDRangeKernel, + /// and finally, map the buffer for reading to make sure + /// there aren't any cache issues when OpenCL completes. + /// + /// + /// + /// + /// + /// + /// + /// + /// + private void DoCrossFade( float ratio, + int width, int height, + Mem input0, int inputStride0, + Mem input1, int inputStride1, + BitmapData output ) + { + Mem outputBuffer; + + int deviceIndex = comboBoxDeviceSelector.SelectedIndex; + + outputBuffer = OCLHelper.Context.CreateBuffer(MemFlags.USE_HOST_PTR, output.Stride * output.Height, output.Scan0); + + CrossFadeGlobalWorkSize[0] = (IntPtr)width; + CrossFadeGlobalWorkSize[1] = (IntPtr)height; + CrossFadeKernel.SetArg(0, ratio); + CrossFadeKernel.SetArg(1, width); + CrossFadeKernel.SetArg(2, height); + CrossFadeKernel.SetArg(3, input0); + CrossFadeKernel.SetArg(4, inputStride0); + CrossFadeKernel.SetArg(5, input1); + CrossFadeKernel.SetArg(6, inputStride1); + CrossFadeKernel.SetArg(7, outputBuffer); + CrossFadeKernel.SetArg(8, output.Stride); + + OCLHelper.CQs[deviceIndex].EnqueueNDRangeKernel(CrossFadeKernel, 2, null, CrossFadeGlobalWorkSize, null); + OCLHelper.CQs[deviceIndex].EnqueueBarrier(); + IntPtr p = OCLHelper.CQs[deviceIndex].EnqueueMapBuffer(outputBuffer, true, MapFlags.READ, IntPtr.Zero, (IntPtr)(output.Stride * output.Height)); + OCLHelper.CQs[deviceIndex].EnqueueUnmapMemObject(outputBuffer, p); + OCLHelper.CQs[deviceIndex].Finish(); + outputBuffer.Dispose(); + } + + private void Form1_Paint(object sender, PaintEventArgs e) + { + Graphics g = e.Graphics; + + if (!Initialized) + { + g.FillRectangle(new SolidBrush(BackColor), 0, 0, Width, Height); + return; + } + + g.FillRectangle(new SolidBrush(BackColor), 0, 0, Width, Height); + g.DrawImageUnscaled(OutputBitmap, 0, 50); + } + + protected override void OnPaintBackground(PaintEventArgs e) + { + } + + private void hScrollBarRatio_ValueChanged(object sender, EventArgs e) + { + if (!Initialized) + return; + + BitmapData bd = OutputBitmap.LockBits(new Rectangle(0, 0, OutputBitmap.Width, OutputBitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + DoCrossFade(hScrollBarRatio.Value*0.01f, + InputBitmapData0.Width, InputBitmapData0.Height, + InputBuffer0, InputBitmapData0.Stride, + InputBuffer1, InputBitmapData1.Stride, + bd); + OutputBitmap.UnlockBits(bd); + Refresh(); + } + + private void comboBoxDeviceSelector_SelectedIndexChanged(object sender, EventArgs e) + { + + } + } +} diff --git a/examples/ImageCrossFade/Form1.resx b/examples/ImageCrossFade/Form1.resx new file mode 100644 index 0000000..c7e0d4b --- /dev/null +++ b/examples/ImageCrossFade/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/examples/ImageCrossFade/ImageCrossFade.csproj b/examples/ImageCrossFade/ImageCrossFade.csproj new file mode 100644 index 0000000..934f2bd --- /dev/null +++ b/examples/ImageCrossFade/ImageCrossFade.csproj @@ -0,0 +1,184 @@ + + + + Debug + AnyCPU + 9.0.21022 + 2.0 + {F7D24581-6EA3-4D20-A722-1BACC34B94AA} + WinExe + Properties + ImageCrossFade + ImageCrossFade + v3.5 + 512 + + + 3.5 + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + AllRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + AllRules.ruleset + + + true + bin\x86\Debug\ + DEBUG;TRACE + full + x86 + prompt + AllRules.ruleset + + + bin\x86\Release\ + TRACE + true + pdbonly + x86 + prompt + AllRules.ruleset + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + + Form + + + Form1.cs + + + + + Form1.cs + Designer + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + PreserveNewest + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + {758285C6-1ACA-458A-9906-EE6701D5AF87} + OpenCLNet + + + + + Input0.png + PreserveNewest + + + Input1.png + PreserveNewest + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + true + + + False + Windows Installer 3.1 + true + + + + + \ No newline at end of file diff --git a/examples/ImageCrossFade/ImageCrossFade.csproj.user b/examples/ImageCrossFade/ImageCrossFade.csproj.user new file mode 100644 index 0000000..bc92236 --- /dev/null +++ b/examples/ImageCrossFade/ImageCrossFade.csproj.user @@ -0,0 +1,22 @@ + + + + true + + + true + + + true + + + + + + + + + en-US + false + + \ No newline at end of file diff --git a/examples/ImageCrossFade/OpenCLFunctions.cl b/examples/ImageCrossFade/OpenCLFunctions.cl new file mode 100644 index 0000000..7fa28df --- /dev/null +++ b/examples/ImageCrossFade/OpenCLFunctions.cl @@ -0,0 +1,20 @@ +kernel void CrossFade( float ratio, + int width, + int height, + global uchar* pInput0, + int inputStride0, + global uchar* pInput1, + int inputStride1, + global uchar* pOutput, + int outputStride ) +{ + size_t x = get_global_id(0); + size_t y = get_global_id(1); + global uchar4* pI0 = (global uchar4*)(pInput0+y*inputStride0); + global uchar4* pI1 = (global uchar4*)(pInput1+y*inputStride1); + global uchar4* pO = (global uchar4*)(pOutput+y*outputStride); + uchar4 mixed; + + mixed = convert_uchar4_sat_rte( mix( convert_float4(pI0[x]), convert_float4(pI1[x]), ratio ) ); + pO[x] = mixed; +} diff --git a/examples/ImageCrossFade/Program.cs b/examples/ImageCrossFade/Program.cs new file mode 100644 index 0000000..1f3429d --- /dev/null +++ b/examples/ImageCrossFade/Program.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Forms; + +namespace ImageCrossFade +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/examples/ImageCrossFade/Properties/AssemblyInfo.cs b/examples/ImageCrossFade/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..2504e8d --- /dev/null +++ b/examples/ImageCrossFade/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ImageFilter")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("ImageFilter")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("315618e7-3602-40a3-bf55-fe4ece44e3e2")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/examples/ImageCrossFade/Properties/Resources.Designer.cs b/examples/ImageCrossFade/Properties/Resources.Designer.cs new file mode 100644 index 0000000..31c545a --- /dev/null +++ b/examples/ImageCrossFade/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace ImageCrossFade.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ImageCrossFade.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/examples/ImageCrossFade/Properties/Resources.resx b/examples/ImageCrossFade/Properties/Resources.resx new file mode 100644 index 0000000..ffecec8 --- /dev/null +++ b/examples/ImageCrossFade/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/examples/ImageCrossFade/Properties/Settings.Designer.cs b/examples/ImageCrossFade/Properties/Settings.Designer.cs new file mode 100644 index 0000000..f73fe80 --- /dev/null +++ b/examples/ImageCrossFade/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace ImageCrossFade.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/examples/ImageCrossFade/Properties/Settings.settings b/examples/ImageCrossFade/Properties/Settings.settings new file mode 100644 index 0000000..abf36c5 --- /dev/null +++ b/examples/ImageCrossFade/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/examples/OpenCLImageTest/Form1.Designer.cs b/examples/OpenCLImageTest/Form1.Designer.cs new file mode 100644 index 0000000..e045008 --- /dev/null +++ b/examples/OpenCLImageTest/Form1.Designer.cs @@ -0,0 +1,214 @@ +namespace OpenCLImageTest +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.buttonScaleImage = new System.Windows.Forms.Button(); + this.groupBoxScaled = new System.Windows.Forms.GroupBox(); + this.panelScaled = new System.Windows.Forms.Panel(); + this.groupBoxOriginal = new System.Windows.Forms.GroupBox(); + this.panelOriginal = new System.Windows.Forms.Panel(); + this.comboBoxOpenCLDevices = new System.Windows.Forms.ComboBox(); + this.label1 = new System.Windows.Forms.Label(); + this.label2 = new System.Windows.Forms.Label(); + this.labelImageSupportIndicator = new System.Windows.Forms.Label(); + this.label3 = new System.Windows.Forms.Label(); + this.comboBoxOpenCLPlatforms = new System.Windows.Forms.ComboBox(); + this.groupBoxCallBackEvents = new System.Windows.Forms.GroupBox(); + this.textBoxCallBackEvents = new System.Windows.Forms.TextBox(); + this.groupBoxScaled.SuspendLayout(); + this.groupBoxOriginal.SuspendLayout(); + this.groupBoxCallBackEvents.SuspendLayout(); + this.SuspendLayout(); + // + // buttonScaleImage + // + this.buttonScaleImage.Location = new System.Drawing.Point(753, 455); + this.buttonScaleImage.Name = "buttonScaleImage"; + this.buttonScaleImage.Size = new System.Drawing.Size(93, 24); + this.buttonScaleImage.TabIndex = 0; + this.buttonScaleImage.Text = "Scale Image"; + this.buttonScaleImage.UseVisualStyleBackColor = true; + this.buttonScaleImage.Click += new System.EventHandler(this.buttonScaleImage_Click); + // + // groupBoxScaled + // + this.groupBoxScaled.Controls.Add(this.panelScaled); + this.groupBoxScaled.Location = new System.Drawing.Point(262, 0); + this.groupBoxScaled.Name = "groupBoxScaled"; + this.groupBoxScaled.Size = new System.Drawing.Size(587, 385); + this.groupBoxScaled.TabIndex = 1; + this.groupBoxScaled.TabStop = false; + this.groupBoxScaled.Text = "Scaled"; + // + // panelScaled + // + this.panelScaled.Dock = System.Windows.Forms.DockStyle.Fill; + this.panelScaled.Location = new System.Drawing.Point(3, 16); + this.panelScaled.Name = "panelScaled"; + this.panelScaled.Size = new System.Drawing.Size(581, 366); + this.panelScaled.TabIndex = 0; + this.panelScaled.Paint += new System.Windows.Forms.PaintEventHandler(this.panelScaled_Paint); + // + // groupBoxOriginal + // + this.groupBoxOriginal.Controls.Add(this.panelOriginal); + this.groupBoxOriginal.Location = new System.Drawing.Point(0, 0); + this.groupBoxOriginal.Name = "groupBoxOriginal"; + this.groupBoxOriginal.Size = new System.Drawing.Size(256, 256); + this.groupBoxOriginal.TabIndex = 2; + this.groupBoxOriginal.TabStop = false; + this.groupBoxOriginal.Text = "Original"; + // + // panelOriginal + // + this.panelOriginal.Dock = System.Windows.Forms.DockStyle.Fill; + this.panelOriginal.Location = new System.Drawing.Point(3, 16); + this.panelOriginal.Name = "panelOriginal"; + this.panelOriginal.Size = new System.Drawing.Size(250, 237); + this.panelOriginal.TabIndex = 0; + this.panelOriginal.Paint += new System.Windows.Forms.PaintEventHandler(this.panelOriginal_Paint); + // + // comboBoxOpenCLDevices + // + this.comboBoxOpenCLDevices.FormattingEnabled = true; + this.comboBoxOpenCLDevices.Location = new System.Drawing.Point(86, 429); + this.comboBoxOpenCLDevices.Name = "comboBoxOpenCLDevices"; + this.comboBoxOpenCLDevices.Size = new System.Drawing.Size(763, 21); + this.comboBoxOpenCLDevices.TabIndex = 3; + this.comboBoxOpenCLDevices.SelectedIndexChanged += new System.EventHandler(this.comboBoxOpenCLDevices_SelectedIndexChanged); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(-3, 432); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(86, 13); + this.label1.TabIndex = 4; + this.label1.Text = "OpenCL Device:"; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(-3, 461); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(77, 13); + this.label2.TabIndex = 5; + this.label2.Text = "Image support:"; + // + // labelImageSupportIndicator + // + this.labelImageSupportIndicator.AutoSize = true; + this.labelImageSupportIndicator.Location = new System.Drawing.Point(83, 461); + this.labelImageSupportIndicator.Name = "labelImageSupportIndicator"; + this.labelImageSupportIndicator.Size = new System.Drawing.Size(0, 13); + this.labelImageSupportIndicator.TabIndex = 6; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(-3, 405); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(90, 13); + this.label3.TabIndex = 8; + this.label3.Text = "OpenCL Platform:"; + // + // comboBoxOpenCLPlatforms + // + this.comboBoxOpenCLPlatforms.FormattingEnabled = true; + this.comboBoxOpenCLPlatforms.Location = new System.Drawing.Point(86, 402); + this.comboBoxOpenCLPlatforms.Name = "comboBoxOpenCLPlatforms"; + this.comboBoxOpenCLPlatforms.Size = new System.Drawing.Size(763, 21); + this.comboBoxOpenCLPlatforms.TabIndex = 7; + this.comboBoxOpenCLPlatforms.SelectedIndexChanged += new System.EventHandler(this.comboBoxOpenCLPlatforms_SelectedIndexChanged); + // + // groupBoxCallBackEvents + // + this.groupBoxCallBackEvents.Controls.Add(this.textBoxCallBackEvents); + this.groupBoxCallBackEvents.Location = new System.Drawing.Point(3, 263); + this.groupBoxCallBackEvents.Name = "groupBoxCallBackEvents"; + this.groupBoxCallBackEvents.Size = new System.Drawing.Size(249, 118); + this.groupBoxCallBackEvents.TabIndex = 9; + this.groupBoxCallBackEvents.TabStop = false; + this.groupBoxCallBackEvents.Text = "CallBack Events"; + // + // textBoxCallBackEvents + // + this.textBoxCallBackEvents.Dock = System.Windows.Forms.DockStyle.Fill; + this.textBoxCallBackEvents.Location = new System.Drawing.Point(3, 16); + this.textBoxCallBackEvents.Multiline = true; + this.textBoxCallBackEvents.Name = "textBoxCallBackEvents"; + this.textBoxCallBackEvents.ReadOnly = true; + this.textBoxCallBackEvents.Size = new System.Drawing.Size(243, 99); + this.textBoxCallBackEvents.TabIndex = 0; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(853, 485); + this.Controls.Add(this.groupBoxCallBackEvents); + this.Controls.Add(this.label3); + this.Controls.Add(this.comboBoxOpenCLPlatforms); + this.Controls.Add(this.labelImageSupportIndicator); + this.Controls.Add(this.label2); + this.Controls.Add(this.label1); + this.Controls.Add(this.comboBoxOpenCLDevices); + this.Controls.Add(this.groupBoxScaled); + this.Controls.Add(this.buttonScaleImage); + this.Controls.Add(this.groupBoxOriginal); + this.Name = "Form1"; + this.Text = "OpenCL Image Test"; + this.Load += new System.EventHandler(this.Form1_Load); + this.groupBoxScaled.ResumeLayout(false); + this.groupBoxOriginal.ResumeLayout(false); + this.groupBoxCallBackEvents.ResumeLayout(false); + this.groupBoxCallBackEvents.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button buttonScaleImage; + private System.Windows.Forms.GroupBox groupBoxScaled; + private System.Windows.Forms.GroupBox groupBoxOriginal; + private System.Windows.Forms.ComboBox comboBoxOpenCLDevices; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Label labelImageSupportIndicator; + private System.Windows.Forms.Panel panelScaled; + private System.Windows.Forms.Panel panelOriginal; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.ComboBox comboBoxOpenCLPlatforms; + private System.Windows.Forms.GroupBox groupBoxCallBackEvents; + private System.Windows.Forms.TextBox textBoxCallBackEvents; + } +} + diff --git a/examples/OpenCLImageTest/Form1.cs b/examples/OpenCLImageTest/Form1.cs new file mode 100644 index 0000000..5a01981 --- /dev/null +++ b/examples/OpenCLImageTest/Form1.cs @@ -0,0 +1,341 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Drawing.Imaging; +using System.Linq; +using System.Text; +using System.Windows.Forms; +using System.IO; +using OpenCLNet; +using CL = OpenCLNet; + +namespace OpenCLImageTest +{ + public partial class Form1 : Form + { + string OpenCLSource; + Bitmap TestImage; + Bitmap TestImageOutput; + + // Currently selected platform + Platform oclPlatform; + // All devices in the currently selected platform + Device[] oclDevices; + // Currently selected device + Device oclDevice; + // Currently active context + Context oclContext; + // Command queue to selected device + CommandQueue oclCQ; + + // Current program+data + CL.Program oclProgram; + CL.Image OCLInputImage; + CL.Image OCLOutputImage; + Sampler OCLSampler; + Kernel FilterKernel; + + bool oclFullyInitialized = false; + ContextNotify oclContextNotify; + List CallBackEventList = new List(); + + public Form1() + { + InitializeComponent(); + oclContextNotify = new ContextNotify(OpenCLContextNotifyCallBack); + } + + public void SetupOpenCL() + { + if (OpenCL.NumberOfPlatforms == 0) + { + MessageBox.Show("OpenCL not available"); + Application.Exit(); + } + } + + public void PopulateOCLPlatformsComboBox() + { + comboBoxOpenCLPlatforms.Items.Clear(); + for (int platformID = 0; platformID < OpenCL.NumberOfPlatforms; platformID++) + { + Platform p = OpenCL.GetPlatform(platformID); + + comboBoxOpenCLPlatforms.Items.Add(p.Vendor+":"+p.Name+" "+p.Version); + } + } + + public void PopulateOCLDevicesComboBox(Platform p, DeviceType deviceType) + { + Device[] devices = p.QueryDevices(deviceType); + comboBoxOpenCLDevices.Items.Clear(); + foreach (Device d in devices) + { + comboBoxOpenCLDevices.Items.Add(d.Vendor + " " + d.Name); + } + } + + public void CreateContext( Platform platform, Device device ) + { + IntPtr[] contextProperties = new IntPtr[] + { + (IntPtr)ContextProperties.PLATFORM, platform.PlatformID, + IntPtr.Zero, IntPtr.Zero + }; + + Device[] devices = new Device[] + { + device + }; + + oclContext = platform.CreateContext(contextProperties, devices, oclContextNotify, IntPtr.Zero); + oclCQ = oclContext.CreateCommandQueue(device, CommandQueueProperties.PROFILING_ENABLE); + } + + public void OpenCLContextNotifyCallBack(string errInfo, byte[] privateInfo, IntPtr cb, IntPtr userData) + { + CallBackEventList.Add( errInfo ); + textBoxCallBackEvents.Lines = CallBackEventList.ToArray(); + } + + public void BuildOCLSource(string source) + { + oclProgram = oclContext.CreateProgramWithSource(source); + oclProgram.Build(); + FilterKernel = oclProgram.CreateKernel("FilterImage"); + } + + public void CreateOCLImages(Context context) + { + OCLInputImage = CreateOCLBitmapFromBitmap(TestImage); + OCLOutputImage = oclContext.CreateImage2D(MemFlags.WRITE_ONLY, CL.ImageFormat.RGBA8U, panelScaled.Width, panelScaled.Height, 0, IntPtr.Zero); + OCLSampler = oclContext.CreateSampler(true, AddressingMode.CLAMP_TO_EDGE, FilterMode.LINEAR); + } + + public void ReleaseDeviceResources() + { + oclFullyInitialized = false; + if (OCLSampler != null) + { + OCLSampler.Dispose(); + OCLSampler = null; + } + if (OCLInputImage != null) + { + OCLInputImage.Dispose(); + OCLInputImage = null; + } + + if (OCLOutputImage != null) + { + OCLOutputImage.Dispose(); + OCLOutputImage = null; + } + + if (FilterKernel != null) + { + FilterKernel.Dispose(); + FilterKernel = null; + } + + if (oclProgram != null) + { + oclProgram.Dispose(); + oclProgram = null; + } + + if (oclCQ != null) + { + oclCQ.Dispose(); + oclCQ = null; + } + + if (oclContext != null) + { + oclContext.Dispose(); + oclContext = null; + } + } + + public void Setup() + { + TestImage = (Bitmap)Bitmap.FromFile(@"Input0.png"); + TestImage = new Bitmap(TestImage, 256, 256); + TestImageOutput = new Bitmap(panelScaled.Width, panelScaled.Height, PixelFormat.Format32bppArgb); + + if (OpenCL.NumberOfPlatforms <= 0) + { + MessageBox.Show("OpenCL not available"); + Application.Exit(); + } + + PopulateOCLPlatformsComboBox(); + oclPlatform = OpenCL.GetPlatform(0); + comboBoxOpenCLPlatforms.SelectedIndex = 0; + } + + public CL.Image CreateOCLBitmapFromBitmap(Bitmap bitmap) + { + CL.Image oclImage; + + BitmapData bd = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + oclImage = oclContext.CreateImage2D((MemFlags)((long)MemFlags.READ_ONLY | (long)MemFlags.COPY_HOST_PTR), + CL.ImageFormat.RGBA8U, bd.Width, bd.Height, bd.Stride, bd.Scan0); + bitmap.UnlockBits(bd); + return oclImage; + } + + public unsafe void CopyOCLBitmapToBitmap(Mem oclBitmap, Bitmap bitmap) + { + IntPtr[] origin = new IntPtr[3]; + IntPtr[] region = new IntPtr[3]; + Mem buffer; + + BitmapData bd = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + buffer = oclContext.CreateBuffer((MemFlags)((long)MemFlags.WRITE_ONLY | (long)MemFlags.USE_HOST_PTR), bd.Height * bd.Stride, bd.Scan0); + origin[0] = (IntPtr)0; + origin[1] = (IntPtr)0; + origin[2] = (IntPtr)0; + region[0] = (IntPtr)bd.Width; + region[1] = (IntPtr)bd.Height; + region[2] = (IntPtr)1; + oclCQ.EnqueueCopyImageToBuffer(oclBitmap, buffer, origin, region, IntPtr.Zero); + oclCQ.EnqueueBarrier(); + IntPtr p = oclCQ.EnqueueMapBuffer(buffer, true, MapFlags.READ, IntPtr.Zero, (IntPtr)(bd.Height * bd.Stride)); + oclCQ.EnqueueUnmapMemObject(buffer, p); + oclCQ.Finish(); + buffer.Dispose(); + bitmap.UnlockBits(bd); + } + + public void ScaleImage() + { + IntPtr[] globalWorkSize = new IntPtr[3]; + + globalWorkSize[0] = (IntPtr)TestImageOutput.Width; + globalWorkSize[1] = (IntPtr)TestImageOutput.Height; + FilterKernel.SetArg(0, 0.0f); + FilterKernel.SetArg(1, 0.0f); + FilterKernel.SetArg(2, 1.0f); + FilterKernel.SetArg(3, 1.0f); + FilterKernel.SetArg(4, 0.0f); + FilterKernel.SetArg(5, 0.0f); + FilterKernel.SetArg(6, 1.0f); + FilterKernel.SetArg(7, 1.0f); + FilterKernel.SetArg(8, OCLInputImage); + FilterKernel.SetArg(9, OCLOutputImage); + FilterKernel.SetArg(10, OCLSampler); + oclCQ.EnqueueNDRangeKernel(FilterKernel, 2, null, globalWorkSize, null); + oclCQ.EnqueueBarrier(); + CopyOCLBitmapToBitmap(OCLOutputImage, TestImageOutput); + oclCQ.Finish(); + } + + private void Form1_Load(object sender, EventArgs e) + { + try + { + Setup(); + } + catch (OpenCLException ocle) + { + MessageBox.Show(ocle.Message); + Application.Exit(); + } + } + + private void buttonScaleImage_Click(object sender, EventArgs e) + { + if (oclFullyInitialized) + { + ScaleImage(); + } + groupBoxScaled.Refresh(); + } + + private void panelOriginal_Paint(object sender, PaintEventArgs e) + { + Graphics g = e.Graphics; + + if (TestImage != null) + g.DrawImageUnscaled(TestImage, 0, 0); + } + + private void panelScaled_Paint(object sender, PaintEventArgs e) + { + Graphics g = e.Graphics; + + if (oclFullyInitialized) + { + if (TestImageOutput != null) + g.DrawImageUnscaled(TestImageOutput, 0, 0); + } + } + + private void comboBoxOpenCLDevices_SelectedIndexChanged(object sender, EventArgs e) + { + bool supportsImages; + bool supportsImageFormat; + + try + { + ReleaseDeviceResources(); + panelScaled.Refresh(); + + oclDevice = oclDevices[comboBoxOpenCLDevices.SelectedIndex]; + CreateContext(oclPlatform, oclDevice); + supportsImages = oclDevice.ImageSupport; + supportsImageFormat = oclContext.SupportsImageFormat(MemFlags.READ_WRITE, MemObjectType.IMAGE2D, ChannelOrder.RGBA, ChannelType.UNSIGNED_INT8); + if (oclDevice.ImageSupport && supportsImageFormat) + { + buttonScaleImage.Enabled = true; + labelImageSupportIndicator.Text = "Yes"; + OpenCLSource = File.ReadAllText(@"OpenCLFunctions.cl"); + BuildOCLSource(OpenCLSource); + CreateOCLImages(oclContext); + oclFullyInitialized = true; + } + else + { + buttonScaleImage.Enabled = false; + labelImageSupportIndicator.Text = "No " + (supportsImageFormat ? "(No Image support at all)" : "(Images supported, but no support for RGBA8888)"); + oclContext = null; + } + } + catch (OpenCLBuildException oclbe) + { + MessageBox.Show(this, oclbe.BuildLogs[0], "OpenCL build error"); + } + catch (OpenCLException ocle) + { + MessageBox.Show(this, ocle.Message, "OpenCL exception"); + } + } + + private void comboBoxOpenCLPlatforms_SelectedIndexChanged(object sender, EventArgs e) + { + try + { + ReleaseDeviceResources(); + + oclPlatform = OpenCL.GetPlatform(comboBoxOpenCLPlatforms.SelectedIndex); + oclDevices = oclPlatform.QueryDevices(DeviceType.ALL); + PopulateOCLDevicesComboBox(oclPlatform, DeviceType.ALL); + if (comboBoxOpenCLDevices.Items.Count > 0) + { + comboBoxOpenCLDevices.SelectedIndex = 0; + } + else + { + oclDevice = null; + } + } + catch (OpenCLException ocle) + { + MessageBox.Show(this, ocle.Message, "OpenCL exception"); + } + } + } +} diff --git a/examples/OpenCLImageTest/Form1.resx b/examples/OpenCLImageTest/Form1.resx new file mode 100644 index 0000000..ff31a6d --- /dev/null +++ b/examples/OpenCLImageTest/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/examples/OpenCLImageTest/OpenCLFunctions.cl b/examples/OpenCLImageTest/OpenCLFunctions.cl new file mode 100644 index 0000000..7302160 --- /dev/null +++ b/examples/OpenCLImageTest/OpenCLFunctions.cl @@ -0,0 +1,58 @@ +kernel void FilterImage( float inputLeft, + float inputTop, + float inputWidth, + float inputHeight, + float outputLeft, + float outputTop, + float outputWidth, + float outputHeight, + read_only image2d_t input, + write_only image2d_t output, + sampler_t sampler ) +{ + size_t x = get_global_id(0); + size_t y = get_global_id(1); + int width = get_global_size(0); + int height = get_global_size(1); + + float nX = x/(float)(width-1); + float nY = y/(float)(height-1); + float inputX = inputLeft+inputWidth*nX; + float inputY = inputTop+inputHeight*nY; + float outputX = outputLeft+width*outputWidth*nX; + float outputY = outputTop+height*outputHeight*nY; + float4 rgba = read_imagef( input, sampler, (float2)(inputX,inputY) ); + write_imagef(output,convert_int2((float2)(outputX,outputY)),rgba); +} +/* +kernel void FilterHorz( read_only image2d_t input, + write_only image2d_t output, + sampler_t sampler, + local float4* pFilter, + int filterWidth ) +{ + int width = get_global_size(0); + int height = get_global_size(1); + float pixelWidth = 1.0f/width; + float pixelHeight = 1.0f/height; + float y = pixelHeight/2+get_global_id(1)*pixelHeight; + int filterWidthHalf = filterWidth/2; + + for( float x=pixelWidth/2; x<1.0f; x+=pixelWidth ) + { + float4 rgba = 0; + for( int df=0; df + + + Debug + AnyCPU + 9.0.21022 + 2.0 + {64E8D6E8-B245-47E4-BA61-9BD000E187FA} + WinExe + Properties + OpenCLImageTest + OpenCLImageTest + v3.5 + 512 + + + 3.5 + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + true + AllRules.ruleset + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + true + AllRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + true + AllRules.ruleset + + + true + bin\x86\Debug\ + DEBUG;TRACE + full + x86 + prompt + true + AllRules.ruleset + + + bin\x86\Release\ + TRACE + true + pdbonly + x86 + prompt + true + AllRules.ruleset + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + + Form + + + Form1.cs + + + + + Form1.cs + Designer + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + PreserveNewest + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + {758285C6-1ACA-458A-9906-EE6701D5AF87} + OpenCLNet + + + + + Input0.png + PreserveNewest + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + true + + + False + Windows Installer 3.1 + true + + + + + \ No newline at end of file diff --git a/examples/OpenCLImageTest/OpenCLImageTest.csproj.user b/examples/OpenCLImageTest/OpenCLImageTest.csproj.user new file mode 100644 index 0000000..deaa7cf --- /dev/null +++ b/examples/OpenCLImageTest/OpenCLImageTest.csproj.user @@ -0,0 +1,31 @@ + + + + true + + + true + + + true + + + true + + + true + + + true + + + + + + + + + en-US + false + + \ No newline at end of file diff --git a/examples/OpenCLImageTest/Program.cs b/examples/OpenCLImageTest/Program.cs new file mode 100644 index 0000000..8c2ecb2 --- /dev/null +++ b/examples/OpenCLImageTest/Program.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Forms; + +namespace OpenCLImageTest +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/examples/OpenCLImageTest/Properties/AssemblyInfo.cs b/examples/OpenCLImageTest/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..ef4e8f8 --- /dev/null +++ b/examples/OpenCLImageTest/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenCLImageTest")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("OpenCLImageTest")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("d51ba871-9ff1-4d35-a993-6d6d60ecfd07")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/examples/OpenCLImageTest/Properties/Resources.Designer.cs b/examples/OpenCLImageTest/Properties/Resources.Designer.cs new file mode 100644 index 0000000..1f4384d --- /dev/null +++ b/examples/OpenCLImageTest/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace OpenCLImageTest.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("OpenCLImageTest.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/examples/OpenCLImageTest/Properties/Resources.resx b/examples/OpenCLImageTest/Properties/Resources.resx new file mode 100644 index 0000000..ffecec8 --- /dev/null +++ b/examples/OpenCLImageTest/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/examples/OpenCLImageTest/Properties/Settings.Designer.cs b/examples/OpenCLImageTest/Properties/Settings.Designer.cs new file mode 100644 index 0000000..4735a8e --- /dev/null +++ b/examples/OpenCLImageTest/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace OpenCLImageTest.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/examples/OpenCLImageTest/Properties/Settings.settings b/examples/OpenCLImageTest/Properties/Settings.settings new file mode 100644 index 0000000..abf36c5 --- /dev/null +++ b/examples/OpenCLImageTest/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/examples/OpenCLTest/Form1.Designer.cs b/examples/OpenCLTest/Form1.Designer.cs new file mode 100644 index 0000000..731f2a8 --- /dev/null +++ b/examples/OpenCLTest/Form1.Designer.cs @@ -0,0 +1,106 @@ +namespace OpenCLTest +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose( bool disposing ) + { + if( disposing && (components != null) ) + { + components.Dispose(); + } + base.Dispose( disposing ); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + this.menuStrip = new System.Windows.Forms.MenuStrip(); + this.commandToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.startToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.stopToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.timer = new System.Windows.Forms.Timer(this.components); + this.menuStrip.SuspendLayout(); + this.SuspendLayout(); + // + // menuStrip + // + this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.commandToolStripMenuItem}); + this.menuStrip.Location = new System.Drawing.Point(0, 0); + this.menuStrip.Name = "menuStrip"; + this.menuStrip.Size = new System.Drawing.Size(656, 24); + this.menuStrip.TabIndex = 0; + this.menuStrip.Text = "menuStrip1"; + // + // commandToolStripMenuItem + // + this.commandToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.startToolStripMenuItem, + this.stopToolStripMenuItem}); + this.commandToolStripMenuItem.Name = "commandToolStripMenuItem"; + this.commandToolStripMenuItem.Size = new System.Drawing.Size(76, 20); + this.commandToolStripMenuItem.Text = "&Command"; + // + // startToolStripMenuItem + // + this.startToolStripMenuItem.Name = "startToolStripMenuItem"; + this.startToolStripMenuItem.Size = new System.Drawing.Size(98, 22); + this.startToolStripMenuItem.Text = "&Start"; + this.startToolStripMenuItem.Click += new System.EventHandler(this.startToolStripMenuItem_Click); + // + // stopToolStripMenuItem + // + this.stopToolStripMenuItem.Enabled = false; + this.stopToolStripMenuItem.Name = "stopToolStripMenuItem"; + this.stopToolStripMenuItem.Size = new System.Drawing.Size(98, 22); + this.stopToolStripMenuItem.Text = "&Stop"; + this.stopToolStripMenuItem.Click += new System.EventHandler(this.stopToolStripMenuItem_Click); + // + // timer + // + this.timer.Interval = 3; + this.timer.Tick += new System.EventHandler(this.timer_Tick); + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(656, 331); + this.Controls.Add(this.menuStrip); + this.MainMenuStrip = this.menuStrip; + this.Name = "Form1"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.menuStrip.ResumeLayout(false); + this.menuStrip.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.MenuStrip menuStrip; + private System.Windows.Forms.ToolStripMenuItem commandToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem startToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem stopToolStripMenuItem; + private System.Windows.Forms.Timer timer; + + } +} + diff --git a/examples/OpenCLTest/Form1.cs b/examples/OpenCLTest/Form1.cs new file mode 100644 index 0000000..26d9ab7 --- /dev/null +++ b/examples/OpenCLTest/Form1.cs @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Windows.Forms; +using System.Diagnostics; +using System.IO; +using System.Drawing.Imaging; +using OpenCLNet; + +namespace OpenCLTest +{ + public partial class Form1 : Form + { + Mandelbrot Mandelbrot; + int FromSetPtr = 0; + int ToSetPtr = 0; + float[,] Sets = new float[2, 4] + { + {-2.0f, 2.0f, 2.0f, -2.0f}, + {-0.17225f, 0.66116f, -0.17115f, 0.660347f}, + }; + + TimeSpan ZoomTime = TimeSpan.FromSeconds(30); + DateTime ZoomStart; + + public Form1() + { + InitializeComponent(); + } + + private void Form1_Load( object sender, EventArgs e ) + { + try + { + Platform platform = OpenCL.GetPlatform(0); + Mandelbrot = new Mandelbrot(platform, Width, Height); + Mandelbrot.AllocBuffers(); + UpdateMandelbrot(); + } + catch (Exception oex) + { + MessageBox.Show( oex.ToString(), "OpenCL Initialization failed" ); + Application.Exit(); + } + } + + protected int Align(int i, int align) + { + return (i + align - 1) / align * align; + } + + protected override void OnPaintBackground(PaintEventArgs e) + { + UpdateMandelbrot(); + } + + public void ZoomMandelbrot() + { + float zoomFactor = (float)((DateTime.Now - ZoomStart).TotalMilliseconds / ZoomTime.TotalMilliseconds); + Mandelbrot.Left = Sets[FromSetPtr, 0]+(float)((Sets[ToSetPtr, 0] - Sets[FromSetPtr, 0]) * zoomFactor); + Mandelbrot.Right = Sets[FromSetPtr, 2] + (float)((Sets[ToSetPtr, 2] - Sets[FromSetPtr, 2]) * zoomFactor); + Mandelbrot.Top = Sets[FromSetPtr, 1] + (float)((Sets[ToSetPtr, 1] - Sets[FromSetPtr, 1]) * zoomFactor); + Mandelbrot.Bottom = Sets[FromSetPtr, 3] + (float)((Sets[ToSetPtr, 3] - Sets[FromSetPtr, 3]) * zoomFactor); + UpdateMandelbrot(); + } + + private void UpdateMandelbrot() + { + Mandelbrot.Calculate(); + + using (Graphics gfx = this.CreateGraphics()) + { + gfx.DrawImageUnscaled(Mandelbrot.Bitmap, 0, 0); + gfx.DrawString("ms per frame="+Mandelbrot.CalculationTimeMS, Font, Brushes.Yellow, new PointF(50.0f, 50.0f)); + } + } + + private void startToolStripMenuItem_Click(object sender, EventArgs e) + { + startToolStripMenuItem.Enabled = false; + stopToolStripMenuItem.Enabled = true; + ToSetPtr = 1; + ZoomStart = DateTime.Now; + timer.Start(); + } + + private void stopToolStripMenuItem_Click(object sender, EventArgs e) + { + startToolStripMenuItem.Enabled = true; + stopToolStripMenuItem.Enabled = false; + ToSetPtr = 0; + ZoomStart = DateTime.Now; + timer.Start(); + } + + private void timer_Tick(object sender, EventArgs e) + { + TimeSpan dt = DateTime.Now - ZoomStart; + if (dt >= ZoomTime) + { + timer.Stop(); + FromSetPtr = ToSetPtr; + } + ZoomMandelbrot(); + } + } +} + +#if false + ErrorCode result; + uint numPlatforms; + IntPtr[] platformIDs; + + // Get number of platforms + result = cl.GetPlatformIDs( 0, null, out numPlatforms ); + if( result!=ErrorCode.SUCCESS ) + throw new Exception( "GetPlatformIDs failed with ErrorCode."+result ); + Debug.WriteLine( "Number of platforms: "+numPlatforms ); + if( numPlatforms==0 ) + throw new Exception( "No openCL platforms available." ); + + // Create an array of platform IDs + platformIDs = new IntPtr[numPlatforms]; + result = cl.GetPlatformIDs( numPlatforms, platformIDs, out numPlatforms ); + if( result!=ErrorCode.SUCCESS ) + throw new Exception( "GetPlatformIDs failed with ErrorCode."+result ); + Debug.WriteLine(""); + + + int[] globSize = new int[3]; + int[] globID = new int[3]; + float left; + float top; + float right; + float bottom; + AlignedArrayFloat aaf; + + private void KernelIterator2d() + { + int activeIndex = globSize.Length-1; + + while( activeIndex>=0 ) + { + MandelBrotKernel( left, top, right, bottom, aaf ); + while( activeIndex>=0 ) + { + globID[activeIndex]++; + if( globID[activeIndex]>=globSize[activeIndex] ) + { + globID[activeIndex] = 0; + activeIndex--; + } + else + { + activeIndex = globSize.Length-1; + break; + } + } + } + } + + private int get_global_size( int dimension ) { return globSize[dimension]; } + private int get_global_id( int dimension ) { return globID[dimension]; } + private void MandelBrotKernel( float left, float top, float right, float bottom, AlignedArrayFloat af ) + { + int width = get_global_size(0); + int height = get_global_size(1); + int cx = get_global_id(0); + int cy = get_global_id(1); + float dx = (right-left)/(float)width; + float dy = (bottom-top)/(float)height; + + float x0 = left+dx*(float)cx; + float y0 = top+dy*(float)cy; + float x = 0.0f; + float y = 0.0f; + int iteration = 0; + int max_iteration = 1000; + + while( x*x-y*y<=(2*2) && iteration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + 132, 17 + + \ No newline at end of file diff --git a/examples/OpenCLTest/MainProgram.cs b/examples/OpenCLTest/MainProgram.cs new file mode 100644 index 0000000..320b4ea --- /dev/null +++ b/examples/OpenCLTest/MainProgram.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Forms; +using OpenCLNet; + +namespace OpenCLTest +{ + static class MainProgram + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault( false ); + Application.Run( new Form1() ); + } + } +} diff --git a/examples/OpenCLTest/Mandelbrot.cl b/examples/OpenCLTest/Mandelbrot.cl new file mode 100644 index 0000000..04484c3 --- /dev/null +++ b/examples/OpenCLTest/Mandelbrot.cl @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +constant uint Palette[17][4] = +{ + { 0x00, 0x00, 0x00, 0xFF}, + { 0x00, 0xA8, 0x76, 0xFF}, + { 0x20, 0x7E, 0x62, 0xFF}, + { 0x00, 0x6D, 0x4C, 0xFF}, + { 0x35, 0xD4, 0xA4, 0xFF}, + { 0x5F, 0xD4, 0xB1, 0xFF}, + { 0x0D, 0x56, 0xA6, 0xFF}, + { 0x27, 0x4F, 0x7D, 0xFF}, + { 0x04, 0x35, 0x6C, 0xFF}, + { 0x41, 0x86, 0xD3, 0xFF}, + { 0x68, 0x9A, 0xD3, 0xFF}, + { 0x4D, 0xDE, 0x00, 0xFF}, + { 0x55, 0xA6, 0x2A, 0xFF}, + { 0x32, 0x90, 0x00, 0xFF}, + { 0x7A, 0xEE, 0x3C, 0xFF}, + { 0x99, 0xEE, 0x6B, 0xFF}, + { 0x99, 0xEE, 0x6B, 0xFF}, +/* + {0x00, 0x00, 0x5a, 0xff,}, + {0x39, 0x8c, 0xdb, 0xff,}, + {0x9b, 0xb9, 0xff, 0xff,}, + {0x4a, 0xae, 0x92, 0xff,}, + {0x4a, 0xae, 0x92, 0xff,},*/ +}; + +#define MAXITER 100 +#define PALETTELENGTH 16 + +constant int8 i8_01234567 = (int8)( 0, 1, 2, 3, 4, 5, 6, 7 ); +constant int8 i8_00000000 = (int8)( 0, 1, 2, 3, 4, 5, 6, 7 ); +constant int8 i8_11111111 = (int8)( 0, 1, 2, 3, 4, 5, 6, 7 ); + +kernel void Mandelbrot( float left, float top, float right, float bottom, int stride, global uchar4* pOutput ) +{ + size_t width = get_global_size(0); + size_t height = get_global_size(1); + size_t cx = get_global_id(0);// + size_t cy = get_global_id(1);// + float dx = (right-left)/(float)width; + float dy = (bottom-top)/(float)height; + + float x0 = left+dx*(float)cx; + float y0 = top+dy*(float)cy; + float x = 0.0f; + float y = 0.0f; + int iteration = 0; + int max_iteration = MAXITER; + + while( x*x-y*y<=(2*2) && iteration + + + Debug + AnyCPU + 9.0.21022 + 2.0 + {68E39C68-7A11-4AF8-9FEA-3147E720D96D} + WinExe + Properties + OpenCLTest + OpenCLTest + v3.5 + 512 + + + 3.5 + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + x86 + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + true + AllRules.ruleset + + + true + bin\x64\Debug\ + DEBUG;TRACE + true + full + x64 + prompt + AllRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + true + AllRules.ruleset + + + true + bin\x86\Debug\ + DEBUG;TRACE + true + full + x86 + prompt + AllRules.ruleset + + + bin\x86\Release\ + TRACE + true + pdbonly + x86 + prompt + true + AllRules.ruleset + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + + Form + + + Form1.cs + + + + + + Form1.cs + Designer + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + Always + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + {758285C6-1ACA-458A-9906-EE6701D5AF87} + OpenCLNet + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + true + + + False + Windows Installer 3.1 + true + + + + + \ No newline at end of file diff --git a/examples/OpenCLTest/OpenCLTest.csproj.user b/examples/OpenCLTest/OpenCLTest.csproj.user new file mode 100644 index 0000000..2b69d67 --- /dev/null +++ b/examples/OpenCLTest/OpenCLTest.csproj.user @@ -0,0 +1,25 @@ + + + + true + + + true + + + true + + + false + + + + + + + + + en-US + false + + \ No newline at end of file diff --git a/examples/OpenCLTest/Properties/AssemblyInfo.cs b/examples/OpenCLTest/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..cc7d935 --- /dev/null +++ b/examples/OpenCLTest/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle( "OpenCLTest" )] +[assembly: AssemblyDescription( "" )] +[assembly: AssemblyConfiguration( "" )] +[assembly: AssemblyCompany( "Microsoft" )] +[assembly: AssemblyProduct( "OpenCLTest" )] +[assembly: AssemblyCopyright( "Copyright © Microsoft 2009" )] +[assembly: AssemblyTrademark( "" )] +[assembly: AssemblyCulture( "" )] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible( false )] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid( "3732edb1-5d60-4c9b-a883-c28c0c67f0bb" )] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion( "1.0.0.0" )] +[assembly: AssemblyFileVersion( "1.0.0.0" )] diff --git a/examples/OpenCLTest/Properties/Resources.Designer.cs b/examples/OpenCLTest/Properties/Resources.Designer.cs new file mode 100644 index 0000000..db080ec --- /dev/null +++ b/examples/OpenCLTest/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace OpenCLTest.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("OpenCLTest.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/examples/OpenCLTest/Properties/Resources.resx b/examples/OpenCLTest/Properties/Resources.resx new file mode 100644 index 0000000..ffecec8 --- /dev/null +++ b/examples/OpenCLTest/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/examples/OpenCLTest/Properties/Settings.Designer.cs b/examples/OpenCLTest/Properties/Settings.Designer.cs new file mode 100644 index 0000000..ef07b4e --- /dev/null +++ b/examples/OpenCLTest/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace OpenCLTest.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/examples/OpenCLTest/Properties/Settings.settings b/examples/OpenCLTest/Properties/Settings.settings new file mode 100644 index 0000000..abf36c5 --- /dev/null +++ b/examples/OpenCLTest/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/examples/OpenCLVBTest/Form1.Designer.vb b/examples/OpenCLVBTest/Form1.Designer.vb new file mode 100644 index 0000000..2e45dfc --- /dev/null +++ b/examples/OpenCLVBTest/Form1.Designer.vb @@ -0,0 +1,38 @@ + _ +Partial Class Form1 + Inherits System.Windows.Forms.Form + + 'Form overrides dispose to clean up the component list. + _ + Protected Overrides Sub Dispose(ByVal disposing As Boolean) + Try + If disposing AndAlso components IsNot Nothing Then + components.Dispose() + End If + Finally + MyBase.Dispose(disposing) + End Try + End Sub + + 'Required by the Windows Form Designer + Private components As System.ComponentModel.IContainer + + 'NOTE: The following procedure is required by the Windows Form Designer + 'It can be modified using the Windows Form Designer. + 'Do not modify it using the code editor. + _ + Private Sub InitializeComponent() + Me.SuspendLayout() + ' + 'Form1 + ' + Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) + Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font + Me.ClientSize = New System.Drawing.Size(834, 659) + Me.Name = "Form1" + Me.Text = "Form1" + Me.ResumeLayout(False) + + End Sub + +End Class diff --git a/examples/OpenCLVBTest/Form1.resx b/examples/OpenCLVBTest/Form1.resx new file mode 100644 index 0000000..ff31a6d --- /dev/null +++ b/examples/OpenCLVBTest/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/examples/OpenCLVBTest/Form1.vb b/examples/OpenCLVBTest/Form1.vb new file mode 100644 index 0000000..736a64f --- /dev/null +++ b/examples/OpenCLVBTest/Form1.vb @@ -0,0 +1,79 @@ +Imports System.IO +Imports System.Drawing.Imaging +Imports OpenCLNet + + +Public Class Form1 + Dim platform As OpenCLNet.Platform + Dim context As OpenCLNet.Context + Dim program As OpenCLNet.Program + Dim kernel As OpenCLNet.Kernel + Dim bitmap As System.Drawing.Bitmap + Dim cq As OpenCLNet.CommandQueue + Dim devices + Dim mandelbrotMemBuffer As OpenCLNet.Mem + + Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load + Try + platform = OpenCLNet.OpenCL.GetPlatform(0) + devices = platform.QueryDevices(DeviceType.ALL) + context = platform.CreateDefaultContext(Nothing, Nothing) + cq = context.CreateCommandQueue(devices(0), 0) + program = context.CreateProgramWithSource(System.IO.File.ReadAllText("Mandelbrot.cl")) + program.Build() + Catch ex As Exception + Print(ex.ToString()) + End Try + + kernel = program.CreateKernel("Mandelbrot") + bitmap = New Bitmap(1024, 1024, System.Drawing.Imaging.PixelFormat.Format32bppArgb) + mandelbrotMemBuffer = context.CreateBuffer(MemFlags.WRITE_ONLY, bitmap.Width * bitmap.Height * 4, Nothing) + End Sub + + Private Sub DrawMandelbrot(ByVal g As Graphics) + CalcMandelbrot() + g.DrawImageUnscaled(bitmap, 0, 0) + End Sub + + Private Sub CalcMandelbrot() + Dim bd = bitmap.LockBits(New Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb) + Dim clEvent As OpenCLNet.Event + Dim globalWorkSize(0 To 1) As IntPtr + Dim eventWaitList(0 To 0) As OpenCLNet.Event + Dim _Left + Dim _Top + Dim _Right + Dim _Bottom + + _Left = -2.0 + _Top = 2.0 + _Right = 2.0 + _Bottom = -2.0 + kernel.SetSingleArg(0, _Left) + kernel.SetSingleArg(1, _Top) + kernel.SetSingleArg(2, _Right) + kernel.SetSingleArg(3, _Bottom) + kernel.SetIntArg(4, bitmap.Width) + kernel.SetMemArg(5, mandelbrotMemBuffer) + + clEvent = Nothing + globalWorkSize(0) = New IntPtr(CType(bd.Width, Long)) + globalWorkSize(1) = New IntPtr(CType(bd.Height, Long)) + cq.EnqueueNDRangeKernel(kernel, 2, Nothing, globalWorkSize, Nothing, 0, Nothing, clEvent) + cq.Finish() + For i = 0 To bitmap.Width - 1 + cq.EnqueueReadBuffer(mandelbrotMemBuffer, False, bitmap.Width * 4 * i, bitmap.Width * 4, bd.Scan0.ToInt32 + bd.Stride * i) + Next i + cq.Finish() + bitmap.UnlockBits(bd) + End Sub + + Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint + Try + DrawMandelbrot(e.Graphics) + + Catch ex As Exception + Print(ex.ToString()) + End Try + End Sub +End Class diff --git a/examples/OpenCLVBTest/Mandelbrot.cl b/examples/OpenCLVBTest/Mandelbrot.cl new file mode 100644 index 0000000..baf3f00 --- /dev/null +++ b/examples/OpenCLVBTest/Mandelbrot.cl @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2009 Olav Kalgraf(olav.kalgraf@gmail.com) + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +constant uint Palette[17][4] = +{ + { 0x00, 0x00, 0x00, 0xFF }, + { 0x00, 0xA8, 0x76, 0xFF }, + { 0x20, 0x7E, 0x62, 0xFF }, + { 0x00, 0x6D, 0x4C, 0xFF }, + { 0x35, 0xD4, 0xA4, 0xFF }, + { 0x5F, 0xD4, 0xB1, 0xFF }, + { 0x0D, 0x56, 0xA6, 0xFF }, + { 0x27, 0x4F, 0x7D, 0xFF }, + { 0x04, 0x35, 0x6C, 0xFF }, + { 0x41, 0x86, 0xD3, 0xFF }, + { 0x68, 0x9A, 0xD3, 0xFF }, + { 0x4D, 0xDE, 0x00, 0xFF }, + { 0x55, 0xA6, 0x2A, 0xFF }, + { 0x32, 0x90, 0x00, 0xFF }, + { 0x7A, 0xEE, 0x3C, 0xFF }, + { 0x99, 0xEE, 0x6B, 0xFF }, + { 0x99, 0xEE, 0x6B, 0xFF }, +/* + {0x00, 0x00, 0x5a, 0xff,}, + {0x39, 0x8c, 0xdb, 0xff,}, + {0x9b, 0xb9, 0xff, 0xff,}, + {0x4a, 0xae, 0x92, 0xff,}, + {0x4a, 0xae, 0x92, 0xff,},*/ +}; + +#define MAXITER 100 +#define PALETTELENGTH 16 + +constant int8 i8_01234567 = (int8)( 0, 1, 2, 3, 4, 5, 6, 7 ); +constant int8 i8_00000000 = (int8)( 0, 1, 2, 3, 4, 5, 6, 7 ); +constant int8 i8_11111111 = (int8)( 0, 1, 2, 3, 4, 5, 6, 7 ); + +__kernel void Mandelbrot( float left, float top, float right, float bottom, int stride, global uchar4* pOutput ) +{ + size_t width = get_global_size(0); + size_t height = get_global_size(1); + size_t cx = get_global_id(0); + size_t cy = get_global_id(1); + float dx = (right-left)/(float)width; + float dy = (bottom-top)/(float)height; + + float x0 = left+dx*(float)cx; + float y0 = top+dy*(float)cy; + float x = 0.0f; + float y = 0.0f; + int iteration = 0; + int max_iteration = MAXITER; + + while( x*x-y*y<=(2*2) && iteration +' This code was generated by a tool. +' Runtime Version:2.0.50727.4918 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + 'NOTE: This file is auto-generated; do not modify it directly. To make changes, + ' or if you encounter build errors in this file, go to the Project Designer + ' (go to Project Properties or double-click the My Project node in + ' Solution Explorer), and make changes on the Application tab. + ' + Partial Friend Class MyApplication + + _ + Public Sub New() + MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) + Me.IsSingleInstance = false + Me.EnableVisualStyles = true + Me.SaveMySettingsOnExit = true + Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses + End Sub + + _ + Protected Overrides Sub OnCreateMainForm() + Me.MainForm = Global.OpenCLVBTest.Form1 + End Sub + End Class +End Namespace diff --git a/examples/OpenCLVBTest/My Project/Application.myapp b/examples/OpenCLVBTest/My Project/Application.myapp new file mode 100644 index 0000000..7b0c597 --- /dev/null +++ b/examples/OpenCLVBTest/My Project/Application.myapp @@ -0,0 +1,11 @@ + + + true + Form1 + false + 0 + true + 0 + 0 + true + diff --git a/examples/OpenCLVBTest/My Project/AssemblyInfo.vb b/examples/OpenCLVBTest/My Project/AssemblyInfo.vb new file mode 100644 index 0000000..55f000f --- /dev/null +++ b/examples/OpenCLVBTest/My Project/AssemblyInfo.vb @@ -0,0 +1,35 @@ +Imports System +Imports System.Reflection +Imports System.Runtime.InteropServices + +' General Information about an assembly is controlled through the following +' set of attributes. Change these attribute values to modify the information +' associated with an assembly. + +' Review the values of the assembly attributes + + + + + + + + + + +'The following GUID is for the ID of the typelib if this project is exposed to COM + + +' Version information for an assembly consists of the following four values: +' +' Major Version +' Minor Version +' Build Number +' Revision +' +' You can specify all the values or you can default the Build and Revision Numbers +' by using the '*' as shown below: +' + + + diff --git a/examples/OpenCLVBTest/My Project/Resources.Designer.vb b/examples/OpenCLVBTest/My Project/Resources.Designer.vb new file mode 100644 index 0000000..559dec7 --- /dev/null +++ b/examples/OpenCLVBTest/My Project/Resources.Designer.vb @@ -0,0 +1,62 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50727.4918 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My.Resources + + 'This class was auto-generated by the StronglyTypedResourceBuilder + 'class via a tool like ResGen or Visual Studio. + 'To add or remove a member, edit your .ResX file then rerun ResGen + 'with the /str option, or rebuild your VS project. + ' + ' A strongly-typed resource class, for looking up localized strings, etc. + ' + _ + Friend Module Resources + + Private resourceMan As Global.System.Resources.ResourceManager + + Private resourceCulture As Global.System.Globalization.CultureInfo + + ' + ' Returns the cached ResourceManager instance used by this class. + ' + _ + Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager + Get + If Object.ReferenceEquals(resourceMan, Nothing) Then + Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("OpenCLVBTest.Resources", GetType(Resources).Assembly) + resourceMan = temp + End If + Return resourceMan + End Get + End Property + + ' + ' Overrides the current thread's CurrentUICulture property for all + ' resource lookups using this strongly typed resource class. + ' + _ + Friend Property Culture() As Global.System.Globalization.CultureInfo + Get + Return resourceCulture + End Get + Set(ByVal value As Global.System.Globalization.CultureInfo) + resourceCulture = value + End Set + End Property + End Module +End Namespace diff --git a/examples/OpenCLVBTest/My Project/Resources.resx b/examples/OpenCLVBTest/My Project/Resources.resx new file mode 100644 index 0000000..ffecec8 --- /dev/null +++ b/examples/OpenCLVBTest/My Project/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/examples/OpenCLVBTest/My Project/Settings.Designer.vb b/examples/OpenCLVBTest/My Project/Settings.Designer.vb new file mode 100644 index 0000000..69bbfc6 --- /dev/null +++ b/examples/OpenCLVBTest/My Project/Settings.Designer.vb @@ -0,0 +1,73 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:2.0.50727.4918 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + _ + Partial Friend NotInheritable Class MySettings + Inherits Global.System.Configuration.ApplicationSettingsBase + + Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) + +#Region "My.Settings Auto-Save Functionality" +#If _MyType = "WindowsForms" Then + Private Shared addedHandler As Boolean + + Private Shared addedHandlerLockObject As New Object + + _ + Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) + If My.Application.SaveMySettingsOnExit Then + My.Settings.Save() + End If + End Sub +#End If +#End Region + + Public Shared ReadOnly Property [Default]() As MySettings + Get + +#If _MyType = "WindowsForms" Then + If Not addedHandler Then + SyncLock addedHandlerLockObject + If Not addedHandler Then + AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings + addedHandler = True + End If + End SyncLock + End If +#End If + Return defaultInstance + End Get + End Property + End Class +End Namespace + +Namespace My + + _ + Friend Module MySettingsProperty + + _ + Friend ReadOnly Property Settings() As Global.OpenCLVBTest.My.MySettings + Get + Return Global.OpenCLVBTest.My.MySettings.Default + End Get + End Property + End Module +End Namespace diff --git a/examples/OpenCLVBTest/My Project/Settings.settings b/examples/OpenCLVBTest/My Project/Settings.settings new file mode 100644 index 0000000..377f56d --- /dev/null +++ b/examples/OpenCLVBTest/My Project/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/examples/OpenCLVBTest/OpenCLVBTest.vbproj b/examples/OpenCLVBTest/OpenCLVBTest.vbproj new file mode 100644 index 0000000..20580bb --- /dev/null +++ b/examples/OpenCLVBTest/OpenCLVBTest.vbproj @@ -0,0 +1,171 @@ + + + + Debug + AnyCPU + 9.0.21022 + 2.0 + {397E0A3D-6B9B-4718-8DA2-421AA5EF8864} + WinExe + OpenCLVBTest.My.MyApplication + OpenCLVBTest + OpenCLVBTest + 512 + WindowsForms + v3.5 + On + Binary + Off + On + + + true + full + true + true + bin\Debug\ + OpenCLVBTest.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + x86 + + + pdbonly + false + true + true + bin\Release\ + OpenCLVBTest.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + true + true + true + bin\x64\Debug\ + OpenCLVBTest.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + full + x64 + + + true + bin\x64\Release\ + OpenCLVBTest.xml + true + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + pdbonly + x64 + + + true + true + true + bin\x86\Debug\ + OpenCLVBTest.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + full + x86 + + + true + bin\x86\Release\ + OpenCLVBTest.xml + true + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + pdbonly + x86 + + + + + + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + + + + + + + + + Form + + + Form1.vb + Form + + + + True + Application.myapp + + + True + True + Resources.resx + + + True + Settings.settings + True + + + + + Form1.vb + Designer + + + VbMyResourcesResXFileCodeGenerator + Resources.Designer.vb + My.Resources + Designer + + + + + Always + + + MyApplicationCodeGenerator + Application.Designer.vb + + + SettingsSingleFileGenerator + My + Settings.Designer.vb + + + + + {758285C6-1ACA-458A-9906-EE6701D5AF87} + OpenCLNet + + + + + \ No newline at end of file diff --git a/examples/OpenCLVBTest/OpenCLVBTest.vbproj.user b/examples/OpenCLVBTest/OpenCLVBTest.vbproj.user new file mode 100644 index 0000000..6839d76 --- /dev/null +++ b/examples/OpenCLVBTest/OpenCLVBTest.vbproj.user @@ -0,0 +1,11 @@ + + + true + + + true + + + true + + \ No newline at end of file diff --git a/vs2010/ImageCrossFade/ImageCrossFade.csproj b/vs2010/ImageCrossFade/ImageCrossFade.csproj new file mode 100644 index 0000000..ec409cf --- /dev/null +++ b/vs2010/ImageCrossFade/ImageCrossFade.csproj @@ -0,0 +1,153 @@ + + + + Debug + x86 + 8.0.30703 + 2.0 + {2C20473B-CD81-422C-B525-33A14F13B1A5} + WinExe + Properties + ImageCrossFade + ImageCrossFade + v4.0 + Client + 512 + + + x86 + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + x86 + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\Debug\ + DEBUG;TRACE + full + AnyCPU + prompt + true + true + + + bin\Release\ + TRACE + true + pdbonly + AnyCPU + prompt + false + false + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + true + true + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + false + false + false + + + + + + + + + + + + + + + + Form1.cs + Form + + + Form1.designer.cs + Form1.cs + + + Program.cs + + + + Form1.resx + Form1.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + OpenCLFunctions.cl + PreserveNewest + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + {0946E1A6-5488-4711-AD10-D54D6A5D2F32} + OpenCLNet + + + + + Input0.png + PreserveNewest + + + Input1.png + PreserveNewest + + + + + \ No newline at end of file diff --git a/vs2010/ImageCrossFade/ImageCrossFade.csproj.user b/vs2010/ImageCrossFade/ImageCrossFade.csproj.user new file mode 100644 index 0000000..96f4b9d --- /dev/null +++ b/vs2010/ImageCrossFade/ImageCrossFade.csproj.user @@ -0,0 +1,9 @@ + + + + true + + + true + + \ No newline at end of file diff --git a/vs2010/ImageCrossFade/Properties/AssemblyInfo.cs b/vs2010/ImageCrossFade/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..65ac114 --- /dev/null +++ b/vs2010/ImageCrossFade/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ImageCrossFade")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("ImageCrossFade")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("6a122d8c-3ad1-475e-b302-8448d9e39678")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/vs2010/ImageCrossFade/Properties/Resources.Designer.cs b/vs2010/ImageCrossFade/Properties/Resources.Designer.cs new file mode 100644 index 0000000..0c68c81 --- /dev/null +++ b/vs2010/ImageCrossFade/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.21006.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace ImageCrossFade.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ImageCrossFade.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/vs2010/ImageCrossFade/Properties/Resources.resx b/vs2010/ImageCrossFade/Properties/Resources.resx new file mode 100644 index 0000000..ffecec8 --- /dev/null +++ b/vs2010/ImageCrossFade/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/vs2010/ImageCrossFade/Properties/Settings.Designer.cs b/vs2010/ImageCrossFade/Properties/Settings.Designer.cs new file mode 100644 index 0000000..c6c5392 --- /dev/null +++ b/vs2010/ImageCrossFade/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.21006.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace ImageCrossFade.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/vs2010/ImageCrossFade/Properties/Settings.settings b/vs2010/ImageCrossFade/Properties/Settings.settings new file mode 100644 index 0000000..abf36c5 --- /dev/null +++ b/vs2010/ImageCrossFade/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/vs2010/OpenCLImageTest/OpenCLImageTest.csproj b/vs2010/OpenCLImageTest/OpenCLImageTest.csproj new file mode 100644 index 0000000..b5c2d98 --- /dev/null +++ b/vs2010/OpenCLImageTest/OpenCLImageTest.csproj @@ -0,0 +1,158 @@ + + + + Debug + x86 + 8.0.30703 + 2.0 + {75B0ED06-EC94-489B-B951-A4D4970A8B94} + WinExe + Properties + OpenCLImageTest + OpenCLImageTest + v4.0 + Client + 512 + + + x86 + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + + + x86 + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + true + + + true + bin\Debug\ + DEBUG;TRACE + full + AnyCPU + prompt + true + true + false + true + + + bin\Release\ + TRACE + true + pdbonly + AnyCPU + prompt + true + true + false + true + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + true + true + false + true + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + true + true + true + + + + + + + + + + + + + + + + Form1.cs + Form + + + Form1.designer.cs + Form1.cs + + + Program.cs + + + AssemblyInfo.cs + + + Resources.Designer.cs + + + Settings.Designer.cs + + + Form1.resx + Form1.cs + + + Resources.resx + + + + + OpenCLFunctions.cl + PreserveNewest + + + Settings.settings + + + + + + + + {0946E1A6-5488-4711-AD10-D54D6A5D2F32} + OpenCLNet + + + + + Input0.png + PreserveNewest + + + + + \ No newline at end of file diff --git a/vs2010/OpenCLImageTest/OpenCLImageTest.csproj.user b/vs2010/OpenCLImageTest/OpenCLImageTest.csproj.user new file mode 100644 index 0000000..96b0f94 --- /dev/null +++ b/vs2010/OpenCLImageTest/OpenCLImageTest.csproj.user @@ -0,0 +1,21 @@ + + + + true + + + true + + + true + + + true + + + true + + + true + + \ No newline at end of file diff --git a/vs2010/OpenCLNet/OpenCLNet.csproj b/vs2010/OpenCLNet/OpenCLNet.csproj new file mode 100644 index 0000000..6c45ea7 --- /dev/null +++ b/vs2010/OpenCLNet/OpenCLNet.csproj @@ -0,0 +1,148 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {0946E1A6-5488-4711-AD10-D54D6A5D2F32} + Library + Properties + OpenCLNet + OpenCLNet + v4.0 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + true + + + true + bin\x64\Debug\ + DEBUG;TRACE + true + full + x64 + prompt + false + false + + + bin\x64\Release\ + TRACE + true + true + pdbonly + x64 + prompt + false + + + true + bin\x86\Debug\ + DEBUG;TRACE + true + full + x86 + prompt + + + bin\x86\Release\ + TRACE + true + true + pdbonly + x86 + prompt + + + + + + + + + + + + + AlignedArray.cs + + + CommandQueue.cs + + + Context.cs + + + Device.cs + + + Enums.cs + + + Event.cs + + + Exceptions.cs + + + Image.cs + + + InteropTools.cs + + + Kernel.cs + + + Mem.cs + + + OpenCL.cs + + + OpenCLAPI.cs + + + Platform.cs + + + Platforms.cs + + + Program.cs + + + Sampler.cs + + + SimpleOCLHelper.cs + + + + + + \ No newline at end of file diff --git a/vs2010/OpenCLNet/OpenCLNet.csproj.user b/vs2010/OpenCLNet/OpenCLNet.csproj.user new file mode 100644 index 0000000..889252f --- /dev/null +++ b/vs2010/OpenCLNet/OpenCLNet.csproj.user @@ -0,0 +1,21 @@ + + + + true + + + true + + + true + + + true + + + true + + + true + + \ No newline at end of file diff --git a/vs2010/OpenCLNet/OpenCLNet.sln b/vs2010/OpenCLNet/OpenCLNet.sln new file mode 100644 index 0000000..3cbec76 --- /dev/null +++ b/vs2010/OpenCLNet/OpenCLNet.sln @@ -0,0 +1,110 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenCLNet", "OpenCLNet.csproj", "{0946E1A6-5488-4711-AD10-D54D6A5D2F32}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitTests", "..\UnitTests\UnitTests.csproj", "{D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenCLTest", "..\OpenCLTest\OpenCLTest.csproj", "{5667200A-99B7-4A42-B170-E7D4371631D6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageCrossFade", "..\ImageCrossFade\ImageCrossFade.csproj", "{2C20473B-CD81-422C-B525-33A14F13B1A5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenCLImageTest", "..\OpenCLImageTest\OpenCLImageTest.csproj", "{75B0ED06-EC94-489B-B951-A4D4970A8B94}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|Mixed Platforms = Debug|Mixed Platforms + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|Mixed Platforms = Release|Mixed Platforms + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Debug|Mixed Platforms.Build.0 = Debug|x86 + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Debug|x64.ActiveCfg = Debug|x64 + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Debug|x64.Build.0 = Debug|x64 + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Debug|x86.ActiveCfg = Debug|x86 + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Debug|x86.Build.0 = Debug|x86 + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Release|Any CPU.Build.0 = Release|Any CPU + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Release|Mixed Platforms.ActiveCfg = Release|x86 + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Release|Mixed Platforms.Build.0 = Release|x86 + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Release|x64.ActiveCfg = Release|x64 + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Release|x64.Build.0 = Release|x64 + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Release|x86.ActiveCfg = Release|x86 + {0946E1A6-5488-4711-AD10-D54D6A5D2F32}.Release|x86.Build.0 = Release|x86 + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Debug|Mixed Platforms.Build.0 = Debug|x86 + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Debug|x64.ActiveCfg = Debug|x64 + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Debug|x64.Build.0 = Debug|x64 + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Debug|x86.ActiveCfg = Debug|x86 + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Debug|x86.Build.0 = Debug|x86 + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Release|Any CPU.Build.0 = Release|Any CPU + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Release|Mixed Platforms.ActiveCfg = Release|x86 + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Release|Mixed Platforms.Build.0 = Release|x86 + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Release|x64.ActiveCfg = Release|x64 + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Release|x64.Build.0 = Release|x64 + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Release|x86.ActiveCfg = Release|x86 + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5}.Release|x86.Build.0 = Release|x86 + {5667200A-99B7-4A42-B170-E7D4371631D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5667200A-99B7-4A42-B170-E7D4371631D6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5667200A-99B7-4A42-B170-E7D4371631D6}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 + {5667200A-99B7-4A42-B170-E7D4371631D6}.Debug|Mixed Platforms.Build.0 = Debug|x86 + {5667200A-99B7-4A42-B170-E7D4371631D6}.Debug|x64.ActiveCfg = Debug|x64 + {5667200A-99B7-4A42-B170-E7D4371631D6}.Debug|x64.Build.0 = Debug|x64 + {5667200A-99B7-4A42-B170-E7D4371631D6}.Debug|x86.ActiveCfg = Debug|x86 + {5667200A-99B7-4A42-B170-E7D4371631D6}.Debug|x86.Build.0 = Debug|x86 + {5667200A-99B7-4A42-B170-E7D4371631D6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5667200A-99B7-4A42-B170-E7D4371631D6}.Release|Any CPU.Build.0 = Release|Any CPU + {5667200A-99B7-4A42-B170-E7D4371631D6}.Release|Mixed Platforms.ActiveCfg = Release|x86 + {5667200A-99B7-4A42-B170-E7D4371631D6}.Release|Mixed Platforms.Build.0 = Release|x86 + {5667200A-99B7-4A42-B170-E7D4371631D6}.Release|x64.ActiveCfg = Release|x64 + {5667200A-99B7-4A42-B170-E7D4371631D6}.Release|x64.Build.0 = Release|x64 + {5667200A-99B7-4A42-B170-E7D4371631D6}.Release|x86.ActiveCfg = Release|x86 + {5667200A-99B7-4A42-B170-E7D4371631D6}.Release|x86.Build.0 = Release|x86 + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Debug|Mixed Platforms.Build.0 = Debug|x86 + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Debug|x64.ActiveCfg = Debug|x64 + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Debug|x64.Build.0 = Debug|x64 + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Debug|x86.ActiveCfg = Debug|x86 + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Debug|x86.Build.0 = Debug|x86 + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Release|Any CPU.Build.0 = Release|Any CPU + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Release|Mixed Platforms.ActiveCfg = Release|x86 + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Release|Mixed Platforms.Build.0 = Release|x86 + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Release|x64.ActiveCfg = Release|x64 + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Release|x64.Build.0 = Release|x64 + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Release|x86.ActiveCfg = Release|x86 + {2C20473B-CD81-422C-B525-33A14F13B1A5}.Release|x86.Build.0 = Release|x86 + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Debug|Any CPU.Build.0 = Debug|Any CPU + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Debug|Mixed Platforms.Build.0 = Debug|x86 + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Debug|x64.ActiveCfg = Debug|x64 + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Debug|x64.Build.0 = Debug|x64 + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Debug|x86.ActiveCfg = Debug|x86 + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Debug|x86.Build.0 = Debug|x86 + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Release|Any CPU.ActiveCfg = Release|Any CPU + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Release|Any CPU.Build.0 = Release|Any CPU + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Release|Mixed Platforms.ActiveCfg = Release|x86 + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Release|Mixed Platforms.Build.0 = Release|x86 + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Release|x64.ActiveCfg = Release|x64 + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Release|x64.Build.0 = Release|x64 + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Release|x86.ActiveCfg = Release|x86 + {75B0ED06-EC94-489B-B951-A4D4970A8B94}.Release|x86.Build.0 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/vs2010/OpenCLNet/OpenCLNet.suo b/vs2010/OpenCLNet/OpenCLNet.suo new file mode 100644 index 0000000..f95b7cf Binary files /dev/null and b/vs2010/OpenCLNet/OpenCLNet.suo differ diff --git a/vs2010/OpenCLNet/Properties/AssemblyInfo.cs b/vs2010/OpenCLNet/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..565b406 --- /dev/null +++ b/vs2010/OpenCLNet/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenCLNet")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("OpenCLNet")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("51e36687-2acd-468d-9eaf-0c3909ea5737")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/vs2010/OpenCLTest/OpenCLTest.csproj b/vs2010/OpenCLTest/OpenCLTest.csproj new file mode 100644 index 0000000..b5c8a91 --- /dev/null +++ b/vs2010/OpenCLTest/OpenCLTest.csproj @@ -0,0 +1,126 @@ + + + + Debug + x86 + 8.0.30703 + 2.0 + {5667200A-99B7-4A42-B170-E7D4371631D6} + Exe + Properties + OpenCLTest + OpenCLTest + v4.0 + Client + 512 + + + x86 + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + + + x86 + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + true + + + true + bin\Debug\ + DEBUG;TRACE + true + full + AnyCPU + prompt + false + false + + + bin\Release\ + TRACE + true + true + pdbonly + AnyCPU + prompt + + + true + bin\x64\Debug\ + DEBUG;TRACE + true + full + x64 + prompt + + + bin\x64\Release\ + TRACE + true + true + pdbonly + x64 + prompt + + + + Form1.cs + Form + + + Form1.designer.cs + Form1.cs + + + MainProgram.cs + + + Mandelbrot.cs + + + + + Form1.resx + Form1.cs + + + + + Mandelbrot.cl + PreserveNewest + + + + + {0946E1A6-5488-4711-AD10-D54D6A5D2F32} + OpenCLNet + + + + + + + + + + + + + \ No newline at end of file diff --git a/vs2010/OpenCLTest/OpenCLTest.csproj.user b/vs2010/OpenCLTest/OpenCLTest.csproj.user new file mode 100644 index 0000000..96b0f94 --- /dev/null +++ b/vs2010/OpenCLTest/OpenCLTest.csproj.user @@ -0,0 +1,21 @@ + + + + true + + + true + + + true + + + true + + + true + + + true + + \ No newline at end of file diff --git a/vs2010/UnitTests/Properties/AssemblyInfo.cs b/vs2010/UnitTests/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..dd830c1 --- /dev/null +++ b/vs2010/UnitTests/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("UnitTests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("UnitTests")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("85bc952d-3ece-4731-855a-671f6c398640")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/vs2010/UnitTests/Properties/Resources.Designer.cs b/vs2010/UnitTests/Properties/Resources.Designer.cs new file mode 100644 index 0000000..26ee153 --- /dev/null +++ b/vs2010/UnitTests/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.21006.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace UnitTests.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("UnitTests.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/vs2010/UnitTests/Properties/Resources.resx b/vs2010/UnitTests/Properties/Resources.resx new file mode 100644 index 0000000..ffecec8 --- /dev/null +++ b/vs2010/UnitTests/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/vs2010/UnitTests/Properties/Settings.Designer.cs b/vs2010/UnitTests/Properties/Settings.Designer.cs new file mode 100644 index 0000000..f2523a4 --- /dev/null +++ b/vs2010/UnitTests/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.21006.1 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace UnitTests.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/vs2010/UnitTests/Properties/Settings.settings b/vs2010/UnitTests/Properties/Settings.settings new file mode 100644 index 0000000..abf36c5 --- /dev/null +++ b/vs2010/UnitTests/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/vs2010/UnitTests/UnitTests.csproj b/vs2010/UnitTests/UnitTests.csproj new file mode 100644 index 0000000..1b5b06f --- /dev/null +++ b/vs2010/UnitTests/UnitTests.csproj @@ -0,0 +1,150 @@ + + + + Debug + x86 + 8.0.30703 + 2.0 + {D1EE52C7-C504-4BE2-9546-315B1E2CA2D5} + WinExe + Properties + UnitTests + UnitTests + v4.0 + Client + 512 + + + x86 + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + + + x86 + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + true + + + true + bin\x64\Debug\ + DEBUG;TRACE + true + full + x64 + prompt + true + true + + + bin\x64\Release\ + TRACE + true + true + pdbonly + x64 + prompt + + + true + bin\Debug\ + DEBUG;TRACE + true + full + AnyCPU + prompt + true + true + + + bin\Release\ + TRACE + true + true + pdbonly + AnyCPU + prompt + false + false + + + + + + + + + + + + + + + + Form1.cs + Form + + + Form1.designer.cs + Form1.cs + + + Program.cs + + + + Form1.resx + Form1.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + Mandelbrot.cl + PreserveNewest + + + MemoryTests.cl + PreserveNewest + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + {0946E1A6-5488-4711-AD10-D54D6A5D2F32} + OpenCLNet + + + + + \ No newline at end of file diff --git a/vs2010/UnitTests/UnitTests.csproj.user b/vs2010/UnitTests/UnitTests.csproj.user new file mode 100644 index 0000000..4711e02 --- /dev/null +++ b/vs2010/UnitTests/UnitTests.csproj.user @@ -0,0 +1,21 @@ + + + + true + + + true + + + true + + + true + + + true + + + true + + \ No newline at end of file