Beispiel #1
0
 internal CommandQueue(CLCommandQueue openclCommandQueue, Context context, Device device, CommandQueueProperties commandQueueProperties)
 {
     this.Device                   = device;
     this.Context                  = context;
     this.CLCommandQueue           = openclCommandQueue;
     this.CLCommandQueueProperties = commandQueueProperties;
 }
Beispiel #2
0
 public static extern CLError clEnqueueReleaseGLObjects(
     CLCommandQueue command_queue,
     uint num_objects,
     [In] CLMem[] mem_objects,
     uint num_events_in_wait_list,
     [In] CLEvent[] event_wait_list,
     ref CLEvent e);
Beispiel #3
0
        /// <summary>
        /// プログラムのコンパイルまでを行います
        /// </summary>
        /// <param name="programSource"></param>
        public static void Initialize(params string[] programSource)
        {
            IntPtr[] device = getDevices(getPlatforms()[0], DeviceType.Default);
            Context = new CLContext(device);

            CommandQueue = new CLCommandQueue(Context, device[0]);

            Program = new CLProgram(Context, programSource);
            Program.Build(Devices);
        }
Beispiel #4
0
 private void SetupCLProgram()
 {
     if (_context != null || _kernels.Count == 0)
     {
         return;
     }
     _context = CLContext.CreateContextForDevices(CLContext.Gpus.First());
     _queue   = new CLCommandQueue(_context);
     _program = new CLProgram(_context, _kernels.ToArray());
 }
Beispiel #5
0
        public static CommandQueue Create(Context context, Device device, CommandQueueProperties commandQueueProperties)
        {
            CLError error = CLError.None;

            CLCommandQueue openclCommandQueue = OpenCLDriver.clCreateCommandQueue(context.CLContext, device.CLDeviceID, (ManOCL.Internal.OpenCL.CLCommandQueueProperties)commandQueueProperties, ref error);

            OpenCLError.Validate(error);

            return(new CommandQueue(openclCommandQueue, context, device, commandQueueProperties));
        }
Beispiel #6
0
        /// <summary>
        /// Setup OpenCL
        /// </summary>
        internal static void Setup()
        {
            try
            {
                // ADD YOUR CODE HERE
                CLError        err;
                uint           num_entries = 0;// get platform
                CLPlatformID[] platforms   = new CLPlatformID[5];
                err = OpenCLDriver.clGetPlatformIDs(5, platforms, ref num_entries);
                if (num_entries == 0)
                {
                    throw new Exception("No Platform Entries found!");
                }
                //get device ID
                CLDeviceID[] devices = new CLDeviceID[1];
                err = OpenCLDriver.clGetDeviceIDs(platforms[0], CLDeviceType.GPU, 1, devices, ref num_entries);
                // create context
                ctx = OpenCLDriver.clCreateContext(null, 1, devices, null, IntPtr.Zero, ref err);
                if (err != CLError.Success)
                {
                    throw new Exception(err.ToString());
                }

                // create command queue
                comQ = OpenCLDriver.clCreateCommandQueue(ctx, devices[0], 0, ref err);
                if (err != CLError.Success)
                {
                    throw new Exception(err.ToString());
                }

                // Compile Program
                string[] progString = new string[1];
                progString[0] = File.ReadAllText("..\\..\\prog.cl");
                program       = OpenCLDriver.clCreateProgramWithSource(ctx, 1, progString, null, ref err);
                err           = OpenCLDriver.clBuildProgram(program, 1, devices, "", null, IntPtr.Zero);

                //create kernel
                kernel_mult = OpenCLDriver.clCreateKernel(program, "multiply", ref err);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }
Beispiel #7
0
        /// <summary>
        /// Setup OpenCL
        /// </summary>
        internal static void Setup()
        {
            try
            {
                // ADD YOUR CODE HERE
                CLError err;
                uint num_entries = 0;// get platform
                CLPlatformID[] platforms = new CLPlatformID[5];
                err = OpenCLDriver.clGetPlatformIDs(5, platforms, ref num_entries);
                if (num_entries == 0) throw new Exception("No Platform Entries found!");
                //get device ID
                CLDeviceID[] devices = new CLDeviceID[1];
                err = OpenCLDriver.clGetDeviceIDs(platforms[0], CLDeviceType.GPU, 1, devices, ref num_entries);
                // create context
                ctx = OpenCLDriver.clCreateContext(null, 1, devices, null, IntPtr.Zero, ref err);
                if (err != CLError.Success) throw new Exception(err.ToString());

                // create command queue
                comQ = OpenCLDriver.clCreateCommandQueue(ctx, devices[0], 0, ref err);
                if (err != CLError.Success) throw new Exception(err.ToString());

                // Compile Program
                string[] progString = new string[1];
                progString[0] = File.ReadAllText("..\\..\\prog.cl");
                program = OpenCLDriver.clCreateProgramWithSource(ctx, 1, progString, null, ref err);
                err = OpenCLDriver.clBuildProgram(program, 1, devices, "", null, IntPtr.Zero);

                //create kernel
                kernel_mult = OpenCLDriver.clCreateKernel(program, "multiply", ref err);

            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            ToGrayscale.ConvertToGrayscale("image.jpg");

            //Get the ids of available opencl platforms

            CL.GetPlatformIds(0, null, out uint platformCount);
            CLPlatform[] platformIds = new CLPlatform[platformCount];
            CL.GetPlatformIds(platformCount, platformIds, out _);

            Console.WriteLine(platformIds.Length);
            foreach (CLPlatform platform in platformIds)
            {
                Console.WriteLine(platform.Handle);
                CL.GetPlatformInfo(platform, PlatformInfo.Name, out byte[] val);
            }

            //Get the device ids for each platform
            foreach (IntPtr platformId in platformIds)
            {
                CL.GetDeviceIds(new CLPlatform(platformId), DeviceType.All, out CLDevice[] deviceIds);

                CLContext context = CL.CreateContext(IntPtr.Zero, (uint)deviceIds.Length, deviceIds, IntPtr.Zero,
                                                     IntPtr.Zero, out CLResultCode result);
                if (result != CLResultCode.Success)
                {
                    throw new Exception("The context couldn't be created.");
                }

                string code = @"
                __kernel void add(__global float* A, __global float* B,__global float* result, const float mul)
                {
                    int i = get_global_id(0);
                    result[i] = (A[i] + B[i])*mul;
                }";

                CLProgram program = CL.CreateProgramWithSource(context, code, out result);

                CL.BuildProgram(program, (uint)deviceIds.Length, deviceIds, null, IntPtr.Zero, IntPtr.Zero);

                CLKernel kernel = CL.CreateKernel(program, "add", out result);

                int     arraySize = 20;
                float[] A         = new float[arraySize];
                float[] B         = new float[arraySize];

                for (int i = 0; i < arraySize; i++)
                {
                    A[i] = 1;
                    B[i] = i;
                }

                CLBuffer bufferA = CL.CreateBuffer(context, MemoryFlags.ReadOnly | MemoryFlags.CopyHostPtr, A,
                                                   out result);
                CLBuffer bufferB = CL.CreateBuffer(context, MemoryFlags.ReadOnly | MemoryFlags.CopyHostPtr, B,
                                                   out result);

                float[] pattern = new float[] { 1, 3, 5, 7 };

                CLBuffer resultBuffer = new CLBuffer(CL.CreateBuffer(context, MemoryFlags.WriteOnly,
                                                                     new UIntPtr((uint)(arraySize * sizeof(float))), IntPtr.Zero, out result));

                try
                {
                    CL.SetKernelArg(kernel, 0, bufferA);
                    CL.SetKernelArg(kernel, 1, bufferB);
                    CL.SetKernelArg(kernel, 2, resultBuffer);
                    CL.SetKernelArg(kernel, 3, -1f);

                    CLCommandQueue commandQueue = new CLCommandQueue(
                        CL.CreateCommandQueueWithProperties(context, deviceIds[0], IntPtr.Zero, out result));

                    CL.EnqueueFillBuffer(commandQueue, bufferB, pattern, UIntPtr.Zero, (UIntPtr)(arraySize * sizeof(float)), null,
                                         out _);

                    //CL.EnqueueNDRangeKernel(commandQueue, kernel, 1, null, new UIntPtr[] {new UIntPtr((uint)A.Length)},
                    //	null, 0, null,  out CLEvent eventHandle);

                    CL.EnqueueNDRangeKernel(commandQueue, kernel, 1, null, new UIntPtr[] { new UIntPtr((uint)A.Length) },
                                            null, 0, null, out CLEvent eventHandle);


                    CL.Finish(commandQueue);

                    CL.SetEventCallback(eventHandle, (int)CommandExecutionStatus.Complete, (waitEvent, data) =>
                    {
                        float[] resultValues = new float[arraySize];
                        CL.EnqueueReadBuffer(commandQueue, resultBuffer, true, UIntPtr.Zero, resultValues, null, out _);

                        StringBuilder line = new StringBuilder();
                        foreach (float res in resultValues)
                        {
                            line.Append(res);
                            line.Append(", ");
                        }

                        Console.WriteLine(line.ToString());
                    });

                    //get rid of the buffers because we no longer need them
                    CL.ReleaseMemoryObject(bufferA);
                    CL.ReleaseMemoryObject(bufferB);
                    CL.ReleaseMemoryObject(resultBuffer);

                    //Release the program kernels and queues
                    CL.ReleaseProgram(program);
                    CL.ReleaseKernel(kernel);
                    CL.ReleaseCommandQueue(commandQueue);
                    CL.ReleaseContext(context);
                    CL.ReleaseEvent(eventHandle);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    throw;
                }
            }
        }
Beispiel #9
0
        public static void Add()
        {
            CLResultCode error = CLResultCode.Success;

            CLPlatform[] platforms = new CLPlatform[1];
            CL.GetPlatformIds(1, platforms, out _);

            CLDevice[] devices = new CLDevice[1];
            CL.GetDeviceIds(platforms[0], DeviceType.All, 1, devices, out _);

            CLContext context = CL.CreateContext(IntPtr.Zero, devices, IntPtr.Zero, IntPtr.Zero, out _);


            CLProgram program =
                CL.CreateProgramWithSource(context, File.ReadAllText("Kernels/add_arrays.cl"), out error);

            error = CL.BuildProgram(program, 1, devices, null, IntPtr.Zero, IntPtr.Zero);

            if (error != CLResultCode.Success)
            {
                throw new Exception(error.ToString());
            }

            CLKernel kernel = CL.CreateKernel(program, "add", out error);

            Span <float> inputA = new float[]
            {
                1, 24, 5, 43, 41, 56
            };
            Span <float> inputB = new float[]
            {
                72, -323, -1, 43, -41, -26
            };
            Span <float> output = stackalloc float[inputA.Length];

            CLBuffer bufferA = CL.CreateBuffer(context, MemoryFlags.ReadOnly | MemoryFlags.CopyHostPtr, inputA, out _);
            CLBuffer bufferB = CL.CreateBuffer(context, MemoryFlags.ReadOnly | MemoryFlags.CopyHostPtr, inputB, out _);

            CLBuffer outputBuffer = CL.CreateBuffer(context, MemoryFlags.WriteOnly, (UIntPtr)(output.Length * sizeof(float)), IntPtr.Zero, out _);

            //For outputs I wouldn't use that also enqueueing a ReadBuffer is needed regardless
            //CLBuffer outputBuffer = CL.CreateBuffer(context, MemoryFlags.WriteOnly | MemoryFlags.UseHostPtr, output, out _);

            CL.SetKernelArg(kernel, 0, bufferA);
            CL.SetKernelArg(kernel, 1, bufferB);
            CL.SetKernelArg(kernel, 2, outputBuffer);

            CLCommandQueue queue = CL.CreateCommandQueueWithProperties(context, devices[0], IntPtr.Zero, out error);

            CL.EnqueueNDRangeKernel(queue, kernel, 1, null,
                                    new[] { (UIntPtr)inputA.Length }, null, 0, null, out _);

            CL.EnqueueReadBuffer(queue, outputBuffer, true, UIntPtr.Zero, output, null, out _);

            foreach (float f in output)
            {
                Console.WriteLine(f);
            }


            CL.ReleaseMemoryObject(bufferA);
            CL.ReleaseMemoryObject(bufferB);
            CL.ReleaseMemoryObject(outputBuffer);
            CL.ReleaseCommandQueue(queue);
            CL.ReleaseKernel(kernel);
            CL.ReleaseProgram(program);
            CL.ReleaseContext(context);
        }
Beispiel #10
0
 internal static extern CLError clEnqueueAcquireGLObjects(CLCommandQueue command_queue, int num_objects, [In] CLMem[] mem_objects, int num_events_in_wait_list, [In] CLEvent[] event_wait_list, ref CLEvent e);
Beispiel #11
0
        public static void ConvertToGrayscale(string inputPath)
        {
            CLResultCode error = CLResultCode.Success;

            //Get a platform
            CLPlatform[] platforms = new CLPlatform[1];
            CL.GetPlatformIds(1, platforms, out _);

            //Get a device
            CLDevice[] devices = new CLDevice[1];
            CL.GetDeviceIds(platforms[0], DeviceType.Gpu, 1, devices, out _);

            //Create a context
            CLContext context = CL.CreateContext(IntPtr.Zero, devices, IntPtr.Zero, IntPtr.Zero, out error);

            if (error != CLResultCode.Success)
            {
                throw new Exception("Error on creating a context");
            }

            //Create the program from source
            CLProgram program =
                CL.CreateProgramWithSource(context, File.ReadAllText("Kernels/grayscale.cl"), out error);

            error = CL.BuildProgram(program, 1, devices, null, IntPtr.Zero, IntPtr.Zero);

            if (error != CLResultCode.Success)
            {
                throw new Exception($"Error on building program: {error}");
            }


            //Get the kernel which we will use
            CLKernel kernel = CL.CreateKernel(program, "grayscale", out error);

            ImageFormat inputImageFormat = new ImageFormat
            {
                ChannelOrder = ChannelOrder.Bgra,
                ChannelType  = ChannelType.UnsignedInteger8
            };

            Bitmap     inputBitmap = new Bitmap(inputPath);
            BitmapData inputData   = inputBitmap.LockBits(new Rectangle(0, 0, inputBitmap.Width, inputBitmap.Height),
                                                          ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

            ImageDescription imageDescription = new ImageDescription()
            {
                ImageType = MemoryObjectType.Image2D,
                Width     = (UIntPtr)inputBitmap.Width,
                Height    = (UIntPtr)inputBitmap.Height,
                Depth     = (UIntPtr)1
            };

            CLImage inputImage = CL.CreateImage(context, MemoryFlags.ReadOnly | MemoryFlags.CopyHostPtr,
                                                ref inputImageFormat, ref imageDescription, inputData.Scan0, out error);

            Bitmap     outputBitmap = new Bitmap(inputBitmap.Width, inputBitmap.Height, PixelFormat.Format32bppArgb);
            BitmapData outputData   = outputBitmap.LockBits(new Rectangle(0, 0, inputBitmap.Width, inputBitmap.Height),
                                                            ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

            CLImage outputImage = CL.CreateImage(context, MemoryFlags.WriteOnly | MemoryFlags.UseHostPtr,
                                                 ref inputImageFormat, ref imageDescription, outputData.Scan0, out error);

            CL.SetKernelArg(kernel, 0, rFact);
            CL.SetKernelArg(kernel, 1, gFact);
            CL.SetKernelArg(kernel, 2, bFact);

            CL.SetKernelArg(kernel, 3, inputImage);
            CL.SetKernelArg(kernel, 4, outputImage);

            CLCommandQueue queue = CL.CreateCommandQueueWithProperties(context, devices[0], IntPtr.Zero, out error);

            CL.EnqueueNDRangeKernel(queue, kernel, 2, new UIntPtr[] { UIntPtr.Zero, UIntPtr.Zero, }, new[]
            {
                (UIntPtr)inputBitmap.Width,
                (UIntPtr)inputBitmap.Height,
            }, null, 0, null, out _);

            CL.EnqueueReadImage(queue, outputImage, 1, new UIntPtr[] { UIntPtr.Zero, UIntPtr.Zero, },
                                new UIntPtr[]
            {
                (UIntPtr)inputBitmap.Width,
                (UIntPtr)inputBitmap.Height,
                (UIntPtr)1,
            }, UIntPtr.Zero, UIntPtr.Zero, outputData.Scan0, 0, null, out _);

            outputBitmap.UnlockBits(outputData);

            outputBitmap.Save("grayscale.png", System.Drawing.Imaging.ImageFormat.Png);

            //Dispose of all things
            inputBitmap.Dispose();
            outputBitmap.Dispose();

            CL.ReleaseMemoryObject(inputImage);
            CL.ReleaseMemoryObject(outputImage);

            CL.ReleaseCommandQueue(queue);
            CL.ReleaseKernel(kernel);
            CL.ReleaseProgram(program);
            CL.ReleaseContext(context);
        }