Пример #1
0
        public Horn_Schunck()
        {
            maxIteration = 10;
            alpha        = 5;
            flowInterval = 3;
            w            = 1;
            eps          = (float)0.01;
            threshold    = (float)0.5;
            pyramidLevel = 0;
            pyramidOn    = 0;
            warps        = 1;
            sources[0]   = File_Handler.getKernelSourceFromLibrary("HornSchunck.cl");

            Platform[] platforms = Cl.GetPlatformIDs(out error);
            Console.WriteLine("Error code: " + error.ToString());
            devices = Cl.GetDeviceIDs(platforms[0], DeviceType.Gpu, out error);
            Console.WriteLine("Error code: " + error.ToString());
            device  = devices[0];
            context = Cl.CreateContext(null, 1, devices, null, IntPtr.Zero, out error);
            Console.WriteLine("Error code: " + error.ToString());
            program = Cl.CreateProgramWithSource(context, 1, sources, null, out error);
            Console.WriteLine("Error code: " + error.ToString());
            Cl.BuildProgram(program, 1, devices, string.Empty, null, IntPtr.Zero);
            commandQueue = Cl.CreateCommandQueue(context, device, CommandQueueProperties.None, out error);
            Console.WriteLine("Error code: " + error.ToString());
        }
Пример #2
0
        public void GetContextByCl()
        {
            IntPtr context = Cl.CreateContext(null, 1, new Device[] { _device }, null, IntPtr.Zero, out ErrorCode _);

            Assert.IsTrue(context != IntPtr.Zero);
            Cl.ReleaseContext(context);
        }
Пример #3
0
 public L1Flow()
 {
     tau          = (float)0.25;
     lambda       = (float)0.15;
     theta        = (float)0.3;
     epsilon      = (float)0.01;
     maxiter      = 1;
     warps        = 1;
     pyramidLevel = 2;
     threshold    = (float)0.5;
     flowInterval = 2;
     sources[0]   = File_Handler.getKernelSourceFromLibrary("TvL1gradrho.cl");
     sources[1]   = File_Handler.getKernelSourceFromLibrary("TvL1_divP_Flow.cl");
     sources[2]   = File_Handler.getKernelSourceFromLibrary("TvL1_calcP.cl");
     Platform[] platforms = Cl.GetPlatformIDs(out error);
     Console.WriteLine("Error code: " + error.ToString());
     devices = Cl.GetDeviceIDs(platforms[0], DeviceType.Gpu, out error);
     Console.WriteLine("Error code: " + error.ToString());
     device  = devices[0];
     context = Cl.CreateContext(null, 1, devices, null, IntPtr.Zero, out error);
     Console.WriteLine("Error code: " + error.ToString());
     program = Cl.CreateProgramWithSource(context, 3, sources, null, out error);
     Console.WriteLine("Error code: " + error.ToString());
     Cl.BuildProgram(program, 1, devices, string.Empty, null, IntPtr.Zero);
     commandQueue = Cl.CreateCommandQueue(context, device, CommandQueueProperties.None, out error);
     Console.WriteLine("Error code: " + error.ToString());
 }
Пример #4
0
        private void init()
        {
            ErrorCode error;

            // Get platform info
            Platform[]    platforms   = Cl.GetPlatformIDs(out error);
            List <Device> devicesList = new List <Device>();

            LogError(error, "Cl.GetPlaformIDs");

            DeviceType deviceType = DeviceType.Default;

            switch (_parameters["DeviceType"])
            {
            case "Gpu":
                deviceType = DeviceType.Gpu;
                break;

            case "Cpu":
                deviceType = DeviceType.Cpu;
                break;

            case "All":
                deviceType = DeviceType.All;
                break;

            case "Accelerator":
                deviceType = DeviceType.Accelerator;
                break;
            }

            // Get available devices
            foreach (Platform platform in platforms)
            {
                string platformName = Cl.GetPlatformInfo(platform, PlatformInfo.Name, out error).ToString();
                Console.WriteLine("Platform: " + platformName);
                LogError(error, "Cl.GetPlatformInfo");
                foreach (Device device in Cl.GetDeviceIDs(platform, deviceType, out error))
                {
                    LogError(error, "Cl.GetDeviceIDs");
                    Console.WriteLine("Device:" + device.ToString());
                    devicesList.Add(device);
                }
            }

            if (devicesList.Count <= 0)
            {
                Console.WriteLine("No devices found.");
                return;
            }

            _device = devicesList[0];
            if (Cl.GetDeviceInfo(_device, DeviceInfo.ImageSupport, out error).CastTo <OpenCL.Net.Bool>() == OpenCL.Net.Bool.False)
            {
                Console.WriteLine("No image support.");
                return;
            }
            _context = Cl.CreateContext(null, 1, new[] { _device }, ContextNotify, IntPtr.Zero, out error);
            LogError(error, "Cl.CreateContext");
        }
Пример #5
0
        /// <summary>
        /// Initializes handle
        /// </summary>
        /// <returns> whether or not the handle was intialized succesfully </returns>
        public void Init()
        {
            Platform[] platforms = Cl.GetPlatformIDs(out _error);
            CLException.CheckException(_error);

            Console.WriteLine("Found " + platforms.Length + " platform(s)");

            InfoBuffer platformNameBuffer = Cl.GetPlatformInfo(platforms[0], PlatformInfo.Name, out _error);

            CLException.CheckException(_error);
            Console.WriteLine(platformNameBuffer.ToString());

            Device[] devices = Cl.GetDeviceIDs(platforms[0], DeviceType.Gpu, out _error);
            CLException.CheckException(_error);
            _device = devices[0];
            InfoBuffer deviceNameBuffer = Cl.GetDeviceInfo(Device, DeviceInfo.Platform, out _error);

            CLException.CheckException(_error);
            Console.WriteLine(deviceNameBuffer.ToString());

            _context = Cl.CreateContext(null, 1, new[] { devices[0] }, null, IntPtr.Zero, out _error);
            CLException.CheckException(_error);
            _queue = Cl.CreateCommandQueue(Context, Device, CommandQueueProperties.None, out _error);
            CLException.CheckException(_error);
        }
Пример #6
0
 public LGFlow()
 {
     alpha        = (float)15;
     mode         = 1;
     w            = (float)1.9;
     kernelSize   = 3;
     sigma        = 0;
     pyramidLevel = 5;
     iteration    = 1;
     flowInterval = 2;
     threshold    = (float)0.5;
     sources[0]   = File_Handler.getKernelSourceFromLibrary("PushImgFlow.cl");
     sources[1]   = File_Handler.getKernelSourceFromLibrary("LocalGlobalFlow1.cl");
     sources[2]   = File_Handler.getKernelSourceFromLibrary("LocalGlobalFlow2.cl");
     sources[3]   = File_Handler.getKernelSourceFromLibrary("LocalGlobalFlow_J.cl");
     sources[4]   = File_Handler.getKernelSourceFromLibrary("LocalGlobalFlow3.cl");
     Platform[] platforms = Cl.GetPlatformIDs(out error);
     Console.WriteLine("Error code: " + error.ToString());
     devices = Cl.GetDeviceIDs(platforms[0], DeviceType.Gpu, out error);
     Console.WriteLine("Error code: " + error.ToString());
     device  = devices[0];
     context = Cl.CreateContext(null, 1, devices, null, IntPtr.Zero, out error);
     Console.WriteLine("Error code: " + error.ToString());
     program = Cl.CreateProgramWithSource(context, 5, sources, null, out error);
     Console.WriteLine("Error code: " + error.ToString());
     Cl.BuildProgram(program, 1, devices, string.Empty, null, IntPtr.Zero);
     commandQueue = Cl.CreateCommandQueue(context, device, CommandQueueProperties.None, out error);
     Console.WriteLine("Error code: " + error.ToString());
 }
Пример #7
0
        public void Run()
        {
            ErrorCode e   = ErrorCode.Unknown;
            uint      num = 0;

            err = Cl.GetPlatformIDs(1, platforms, out num);
            InfoBuffer platformbuf = Cl.GetPlatformInfo(platforms[0], PlatformInfo.Name, out e);

            device = Cl.GetDeviceIDs(platforms[0], DeviceType.Gpu, out e);
            InfoBuffer devicebuf = Cl.GetDeviceInfo(device[0], DeviceInfo.Name, out e);

            IntPtr ptr  = new IntPtr();
            IntPtr ptr2 = new IntPtr();

            context = Cl.CreateContext(null, 1, new[] { device[0] }, null, ptr, out e);

            InfoBuffer contextbuff = new InfoBuffer();

            e = Cl.GetContextInfo(context, ContextInfo.Devices, ptr, contextbuff, out ptr2);

            Program pg = Cl.CreateProgramWithSource(context, 1, new[] { correctSource }, null, out e);

            e = Cl.BuildProgram(pg, 1, new[] { device[0] }, string.Empty, null, IntPtr.Zero);

            InfoBuffer pgbuild = Cl.GetProgramBuildInfo(pg, device[0], ProgramBuildInfo.Log, out e);
//            Cl.BuildProgram(pg,1,device,"-cl-std=CL")
        }
Пример #8
0
        public void SetUp()
        {
            device = (from platformid in Cl.GetPlatformIDs(out error)
                      from deviceid in Cl.GetDeviceIDs(platformid, Cl.DeviceType.Gpu, out error)
                      select deviceid).First();

            context = Cl.CreateContext(null, 1, new[] { device }, null, IntPtr.Zero, out error);
        }
Пример #9
0
        public static void Main(string[] args)
        {
            int  dimX = GetParameter("--dimX", 322, args);
            int  dimY = GetParameter("--dimY", 242, args);
            int  N    = GetParameter("--N", 97760, args);
            bool lmem = GetFlag("--lmem", args);

            Console.WriteLine("Poisson equation solver: dimX = {0} dimY = {1} N = {2}, LMem: {3}", dimX, dimY, N, lmem);
            string options = string.Join(" ", args.Where(arg => arg.IndexOf("--") == -1));

            Console.WriteLine("OpenCL program build options: " + options);

            Cl.ErrorCode error;

            Cl.Device device = (from platformid in Cl.GetPlatformIDs(out error)
                                from deviceid in Cl.GetDeviceIDs(platformid, Cl.DeviceType.Gpu, out error)
                                select deviceid).First();
            clSafeCall(error);

            Cl.Context context = Cl.CreateContext(null, 1, new[] { device }, null, IntPtr.Zero, out error);
            clSafeCall(error);

            // create program from C# kernel
            IRBuildOptions.AutoInline     = GetFlag("--inline", args);
            IRBuildOptions.WasteRegisters = GetFlag("--rwaste", args);
            Console.WriteLine("IR code build options: AutoInline: {0}; WasteRegisters: {1}",
                              IRBuildOptions.AutoInline, IRBuildOptions.WasteRegisters);
            Cl.Program pcsharp = typeof(MainClass).BuildIR().ToGPUClProgram(device, context);

            // create program from OpenCL kernel
            Cl.Program popencl = Cl.CreateProgramWithSource(context, 1, new[] { PoissonRBSORCl }, null, out error);
            clSafeCall(error);

            // perform bandwidth comparison

            float x0    = (float)(-0.5 * Math.PI);
            float y0    = (float)(-0.5 * Math.PI);
            float x1    = -x0;
            float y1    = -y0;
            float omega = 0.8f;

            Console.WriteLine("C# benchmark:");
            long tcsharp = PoissonRBSOR(device, context, pcsharp, lmem,
                                        x0, y0, x1, y1, dimX, dimY, N, omega, "unigpu.bin", options);

            pcsharp.Dispose();

            Console.WriteLine("OpenCL benchmark:");
            long topencl = PoissonRBSOR(device, context, popencl, lmem,
                                        x0, y0, x1, y1, dimX, dimY, N, omega, "opencl.bin", options);

            popencl.Dispose();

            Console.WriteLine("OpenCL advantage: {0}", (double)tcsharp / (double)topencl);

            context.Dispose();
        }
Пример #10
0
        public static void initOpenCL()
        {
            var           platforms   = Cl.GetPlatformIDs(out error);
            List <Device> devicesList = new List <Device>();

            CheckErr(error, "Cl.GetPlatformIDs");

            foreach (Platform platform in platforms)
            {
                string platformName = Cl.GetPlatformInfo(platform, PlatformInfo.Name, out error).ToString();
                Console.WriteLine("Platform: " + platformName);
                CheckErr(error, "Cl.GetPlatformInfo");
                //We will be looking only for GPU devices
                foreach (Device device in Cl.GetDeviceIDs(platform, DeviceType.Gpu, out error))
                {
                    CheckErr(error, "Cl.GetDeviceIDs");

                    var vendor   = Cl.GetDeviceInfo(device, DeviceInfo.Vendor, out error);
                    var name     = Cl.GetDeviceInfo(device, DeviceInfo.Name, out error);
                    var worksize = Cl.GetDeviceInfo(device, DeviceInfo.MaxWorkGroupSize, out error);
                    var maxCU    = Cl.GetDeviceInfo(device, DeviceInfo.MaxComputeUnits, out error);

                    Console.WriteLine("Vendor: " + vendor + " , " + name);

                    Console.WriteLine("Device: " + device.GetType());
                    Console.WriteLine("Workgroupsize: " + worksize.CastTo <long>());
                    Console.WriteLine("CUS: " + maxCU.CastTo <int>());
                    devicesList.Add(device);
                }
            }

            if (devicesList.Count <= 0)
            {
                Console.WriteLine("No devices found.");
                return;
            }

            _device = devicesList[0];

            if (Cl.GetDeviceInfo
                    (_device,
                    DeviceInfo.ImageSupport,
                    out
                    error).CastTo <Bool>() == Bool.False)
            {
                Console.WriteLine("No image support.");
                return;
            }
            cxGPUContext = Cl.CreateContext(null, 1, new[] { _device }, ContextNotify, IntPtr.Zero, out error); //Second parameter is amount of devices
            CheckErr(error, "Cl.CreateContext");

            cqCommandQueue = Cl.CreateCommandQueue(cxGPUContext, _device, (CommandQueueProperties)0, out error);
            CheckErr(error, "Cl.CreateCommandQueue");

            sort = new GPURadixSort(cqCommandQueue, cxGPUContext, _device);
        }
Пример #11
0
        private void SetupDevice()
        {
            Event     e;
            ErrorCode error;

            Platform[] platforms = Cl.GetPlatformIDs(out error);
            Device[]   devices   = Cl.GetDeviceIDs(platforms[0], DeviceType.Gpu, out error);
            device  = devices[0];
            context = Cl.CreateContext(null, 1, devices, null, IntPtr.Zero, out error);
            queue   = Cl.CreateCommandQueue(context, device, CommandQueueProperties.None, out error);
        }
Пример #12
0
        /// <summary>
        /// Laden der GPU und Eigenschaften
        /// </summary>
        static EasyClCompiler()
        {
            _hasDevice = false;

            Platform[] platforms = Cl.GetPlatformIDs(out ErrorCode error);
            if (error != ErrorCode.Success)
            {
                throw new GPUException("Paltform", error.ToString());
            }

            List <Device> devices = new List <Device>();

            if (platforms.Length > 0)
            {
                foreach (Platform platform in platforms)
                {
                    foreach (Device device in Cl.GetDeviceIDs(platform, DeviceType.Gpu, out error))
                    {
                        if (error != ErrorCode.Success)
                        {
                            throw new GPUException("Device", error.ToString());
                        }
                        devices.Add(device);
                    }
                }
            }

            if (devices.Count > 0)
            {
                foreach (Device device in devices)
                {
                    if (Cl.GetDeviceInfo(device, DeviceInfo.ImageSupport, out error).CastTo <bool>())
                    {
                        Context context = Cl.CreateContext(null, 1, new[] { device }, null, IntPtr.Zero, out error);
                        if (error != ErrorCode.Success)
                        {
                            throw new GPUException("Init", error.ToString());
                        }
                        _device       = device;
                        _context      = context;
                        _commandQueue = Cl.CreateCommandQueue(_context, _device, CommandQueueProperties.None, out _);
                        _hasDevice    = true;
                    }
                }
            }

            #region Init Basic

            _memFlags    = MemFlags.CopyHostPtr;
            _imageFormat = new ImageFormat(ChannelOrder.BGRA, ChannelType.Unsigned_Int8);
            _originPtr   = new[] { (IntPtr)0, (IntPtr)0, (IntPtr)0 };

            #endregion Init Basic
        }
Пример #13
0
        /**
         * Create for a given platform and device.
         */
        public ExecutionContext(Platform platform, Device device)
        {
            Platform = platform;
            Device   = device;

            OpenClContext = Cl.CreateContext(null, 1, new[] { Device }, null, IntPtr.Zero, out var error);
            if (error != ErrorCode.Success)
            {
                throw new NerotiqException($"Unable to create opencl context: {error}");
            }
        }
Пример #14
0
        public APITests()
        {
            ErrorCode error;

            _device = (from device in
                       Cl.GetDeviceIDs(
                           (from platform in Cl.GetPlatformIDs(out error)
                            where Cl.GetPlatformInfo(platform, PlatformInfo.Name, out error).ToString() == "AMD Accelerated Parallel Processing"     // Use "NVIDIA CUDA" if you don't have amd
                            select platform).First(), DeviceType.Gpu, out error)
                       select device).First();

            _context = Cl.CreateContext(null, 1, new[] { _device }, null, IntPtr.Zero, out error);
        }
Пример #15
0
        public void Setup()
        {
            ErrorCode error;

            _device = (from device in
                       Cl.GetDeviceIDs(
                           (from platform in Cl.GetPlatformIDs(out error)
                            where Cl.GetPlatformInfo(platform, PlatformInfo.Name, out error).ToString() == "NVIDIA CUDA"
                            select platform).First(), DeviceType.Gpu, out error)
                       select device).First();

            _context = Cl.CreateContext(null, 1, new[] { _device }, null, IntPtr.Zero, out error);
        }
Пример #16
0
        public void ContextCreation()
        {
            ErrorCode error;

            // Select the device we want
            var device = (from dev in Cl.GetDeviceIDs(
                              (from platform in Cl.GetPlatformIDs(out error)
                               select platform).First(), DeviceType.Gpu, out error)
                          select dev).First();

            uint refCount;

            using (Context context = Cl.CreateContext(null, 1, new[] { device }, null, IntPtr.Zero, out error))
                refCount = Cl.GetContextInfo(context, ContextInfo.ReferenceCount, out error).CastTo <uint>();
        }
Пример #17
0
        public void Setup()
        {
            ErrorCode error;

            Platform[]    platforms   = Cl.GetPlatformIDs(out error);
            List <Device> devicesList = new List <Device>();

            CheckErr(error, "Cl.GetPlatformIDs");

            foreach (Platform platform in platforms)
            {
                //ToDO:Log Platform Device Name;
                //		status = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(pbuff), pbuff, NULL);
                //		status = clGetPlatformInfo(platform, CL_PLATFORM_VERSION, sizeof(pbuff), pbuff, NULL);
                //		status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0, NULL, &numDevices);
                //ToDO: Saved the compiled version so it can be built the next time as a binary:
                //ToDO:  Enable certain cards, fan control, scheduling

                string platformName = Cl.GetPlatformInfo(platform, PlatformInfo.Name, out error).ToString();
                Console.WriteLine("Platform: " + platformName);
                CheckErr(error, "Cl.GetPlatformInfo");

                //We will be looking only for GPU devices
                foreach (OpenCL.Net.Device device in Cl.GetDeviceIDs(platform, DeviceType.Gpu, out error))
                {
                    CheckErr(error, "Cl.GetDeviceIDs");
                    Console.WriteLine("Device: " + device.ToString());
                    devicesList.Add(device);
                }
            }

            if (devicesList.Count <= 0)
            {
                Console.WriteLine("No devices found.");
                return;
            }

            _device = devicesList[0];

            if (Cl.GetDeviceInfo(_device, OpenCL.Net.DeviceInfo.ImageSupport, out error).CastTo <OpenCL.Net.Bool>() == OpenCL.Net.Bool.False)
            {
                Console.WriteLine("No image support.");
                return;
            }

            _context = Cl.CreateContext(null, 1, new[] { _device }, ContextNotify, IntPtr.Zero, out error); //Second parameter is amount of devices
            CheckErr(error, "Cl.CreateContext");
        }
Пример #18
0
        public void GetContextByClWithPlattform()
        {
            throw new NotSupportedException("");
            IntPtr context = Cl.CreateContext(
                new ContextProperty[] {
                new ContextProperty(ContextProperties.Platform, _platforms.First().Handle)
            },
                1,
                new Device[] {
                _device
            },
                null,
                IntPtr.Zero,
                out ErrorCode _
                );

            Assert.IsTrue(context != IntPtr.Zero);
            Cl.ReleaseContext(context);
        }
Пример #19
0
        public static bool Init()
        {
            if (initialized)
            {
                return(true);
            }

            initialized = true;
            ErrorCode error;

            Platform[] platforms = Cl.GetPlatformIDs(out error);
            ErrorCheck(error, "Cl.GetPlatformIDs");

            List <Device> devicesList = new List <Device>();

            foreach (Platform platform in platforms)
            {
                string platformName = Cl.GetPlatformInfo(platform, PlatformInfo.Name, out error).ToString();
                ErrorCheck(error, "Cl.GetPlatformInfo");

                foreach (Device device in Cl.GetDeviceIDs(platform, DeviceType.Gpu, out error))
                {
                    devicesList.Add(device);
                }
            }

            if (devicesList.Count == 0)
            {
                return(false);
            }


            device = devicesList[0];

            //Second parameter is amount of devices
            context = Cl.CreateContext(null, 1, new[] { device }, ContextNotify, IntPtr.Zero, out error);
            ErrorCheck(error, "Cl.CreateContext");

            string crackHigh = Path.Combine(System.Environment.CurrentDirectory, "CrackHigh.cl");

            LoadKernel(crackHigh, "CrackHigh", out crackHighProgram, out crackHighKernel);
            return(true);
        }
Пример #20
0
        public static void Setup()
        {
            ErrorCode err;

            Platform[]    platforms = Cl.GetPlatformIDs(out err);
            List <Device> CLDevices = new List <Device>();

            CheckErr(err, "Cl.GetPlatformIDs");

            foreach (Platform p in platforms)
            {
                string platformName = Cl.GetPlatformInfo(p, PlatformInfo.Name, out err).ToString();

                Console.WriteLine($"Platform: {platformName}");
                CheckErr(err, "Cl.GetPlatformInfo");

                //Limit platforms to GPU-based platforms
                foreach (Device d in Cl.GetDeviceIDs(p, DeviceType.Gpu, out err))
                {
                    CheckErr(err, "Cl.GetDeviceIDs");
                    Console.WriteLine("Device: " + d.ToString());
                    CLDevices.Add(d);
                }
            }

            if (CLDevices.Count <= 0)
            {
                Console.Error.WriteLine("No suitable OpenCL devices found.");
                return;
            }

            _device = CLDevices[0];

            if (Cl.GetDeviceInfo(_device, DeviceInfo.ImageSupport, out err).CastTo <Bool>() == Bool.False)
            {
                Console.Error.WriteLine($"Selected CL device {_device.ToString()} does not have image support.");
                return;
            }

            _context = Cl.CreateContext(null, 1, new Device[] { _device }, ContextNotify, IntPtr.Zero, out err);
            CheckErr(err, "Cl.CreateContext");
        }
Пример #21
0
    public OpenCLHelp()
    {
        ErrorCode error;

        Platform[]    platforms   = Cl.GetPlatformIDs(out error);
        List <Device> devicesList = new List <Device>();

        CheckErr(error, "Cl.GetPlatformIDs");

        foreach (Platform platform in platforms)
        {
            string platformName = Cl.GetPlatformInfo(platform, PlatformInfo.Name, out error).ToString();
            Console.WriteLine("Platform: " + platformName);
            CheckErr(error, "Cl.GetPlatformInfo");
            //We will be looking only for GPU devices
            foreach (Device device in Cl.GetDeviceIDs(platform, DeviceType.Gpu, out error))
            {
                CheckErr(error, "Cl.GetDeviceIDs");
                Console.WriteLine("Device: " + device.ToString());
                devicesList.Add(device);
            }
        }

        if (devicesList.Count <= 0)
        {
            Console.WriteLine("No devices found.");
            return;
        }

        _device = devicesList[0];

        if (Cl.GetDeviceInfo(_device, DeviceInfo.ImageSupport,
                             out error).CastTo <Bool>() == Bool.False)
        {
            Console.WriteLine("No image support.");
            return;
        }
        _context
            = Cl.CreateContext(null, 1, new[] { _device }, ContextNotify,
                               IntPtr.Zero, out error); //Second parameter is amount of devices
        CheckErr(error, "Cl.CreateContext");
    }
Пример #22
0
        public ComputeProvider(params Device[] devices)
        {
            if (devices == null)
            {
                throw new ArgumentNullException("devices");
            }
            if (devices.Length == 0)
            {
                throw new ArgumentException("Need at least one device!");
            }

            _devices = devices;

            ErrorCode error;

            _context = Cl.CreateContext(null, (uint)devices.Length, _devices, null, IntPtr.Zero, out error);

            if (error != ErrorCode.Success)
            {
                throw new Cl.Exception(error);
            }
        }
        private void ready()
        {
            ErrorCode error;

            context = Cl.CreateContext(null, 1, new[] { device }, null, IntPtr.Zero, out error);

            string source = System.IO.File.ReadAllText("kernels.cl");

            program = Cl.CreateProgramWithSource(context, 1, new[] { source }, null, out error);

            error = Cl.BuildProgram(program, 1, new[] { device }, string.Empty, null, IntPtr.Zero);
            InfoBuffer buildStatus = Cl.GetProgramBuildInfo(program, device, ProgramBuildInfo.Status, out error);

            if (buildStatus.CastTo <BuildStatus>() != BuildStatus.Success)
            {
                throw new Exception($"OpenCL could not build the kernel successfully: {buildStatus.CastTo<BuildStatus>()}");
            }
            allGood(error);

            Kernel[] kernels = Cl.CreateKernelsInProgram(program, out error);
            kernel = kernels[0];
            allGood(error);

            queue = Cl.CreateCommandQueue(context, device, CommandQueueProperties.None, out error);
            allGood(error);

            dataOut = Cl.CreateBuffer(context, MemFlags.WriteOnly, (IntPtr)(globalSize * sizeof(int)), out error);
            allGood(error);

            var intSizePtr = new IntPtr(Marshal.SizeOf(typeof(int)));

            error |= Cl.SetKernelArg(kernel, 2, new IntPtr(Marshal.SizeOf(typeof(IntPtr))), dataOut);
            error |= Cl.SetKernelArg(kernel, 3, intSizePtr, new IntPtr(worldSeed));
            error |= Cl.SetKernelArg(kernel, 4, intSizePtr, new IntPtr(globalSize));
            allGood(error);
        }
Пример #24
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            uint      platformCount;
            ErrorCode result = Cl.GetPlatformIDs(0, null, out platformCount);

            Console.WriteLine("{0} platforms found", platformCount);


            var platformIds = new Platform[platformCount];

            result = Cl.GetPlatformIDs(platformCount, platformIds, out platformCount);
            var platformCounter = 0;

            foreach (var platformId in platformIds)
            {
                IntPtr paramSize;
                result = Cl.GetPlatformInfo(platformId, PlatformInfo.Name, IntPtr.Zero, InfoBuffer.Empty, out paramSize);

                using (var buffer = new InfoBuffer(paramSize))
                {
                    result = Cl.GetPlatformInfo(platformIds[0], PlatformInfo.Name, paramSize, buffer, out paramSize);

                    Console.WriteLine($"Platform {platformCounter}: {buffer}");
                }
                platformCounter++;
            }

            Console.WriteLine($"Using first platform...");

            uint deviceCount;

            result = Cl.GetDeviceIDs(platformIds[0], DeviceType.All, 0, null, out deviceCount);
            Console.WriteLine("{0} devices found", deviceCount);

            var deviceIds = new Device[deviceCount];

            result = Cl.GetDeviceIDs(platformIds[0], DeviceType.All, deviceCount, deviceIds, out var numberDevices);

            var selectedDevice = deviceIds[0];

            var context = Cl.CreateContext(null, 1, new[] { selectedDevice }, null, IntPtr.Zero, out var error);

            const string kernelSrc = @"
            // Simple test; c[i] = a[i] + b[i]
            __kernel void add_array(__global float *a, __global float *b, __global float *c)
            {
                int xid = get_global_id(0);
                c[xid] = a[xid] + b[xid] - 1500;
            }
            
            __kernel void sub_array(__global float *a, __global float *b, __global float *c)
            {
                int xid = get_global_id(0);
                c[xid] = a[xid] - b[xid] - 2000;
            }
                        
            __kernel void double_everything(__global float *a)
            {
                int xid = get_global_id(0);
                a[xid] = a[xid] * 2;
            }

            ";


            var src = kernelSrc;

            Console.WriteLine("=== src ===");
            Console.WriteLine(src);
            Console.WriteLine("============");

            var program = Cl.CreateProgramWithSource(context, 1, new[] { src }, null, out var error2);

            error2 = Cl.BuildProgram(program, 1, new[] { selectedDevice }, string.Empty, null, IntPtr.Zero);

            if (error2 == ErrorCode.BuildProgramFailure)
            {
                Console.Error.WriteLine(Cl.GetProgramBuildInfo(program, selectedDevice, ProgramBuildInfo.Log, out error));
            }

            Console.WriteLine(error2);

            // Get the kernels.
            var kernels = Cl.CreateKernelsInProgram(program, out error);

            Console.WriteLine($"Program contains {kernels.Length} kernels.");
            var kernelAdd    = kernels[0];
            var kernelDouble = kernels[2];

            //
            float[] A = new float[1000];
            float[] B = new float[1000];
            float[] C = new float[1000];

            for (var i = 0; i < 1000; i++)
            {
                A[i] = i;
                B[i] = i;
            }

            IMem <float> hDeviceMemA = Cl.CreateBuffer(context, MemFlags.CopyHostPtr | MemFlags.ReadOnly, A, out error);
            IMem <float> hDeviceMemB = Cl.CreateBuffer(context, MemFlags.CopyHostPtr | MemFlags.ReadOnly, B, out error);
            IMem <float> hDeviceMemC = Cl.CreateBuffer(context, MemFlags.CopyHostPtr | MemFlags.ReadOnly, C, out error);

            // Create a command queue.
            var cmdQueue = Cl.CreateCommandQueue(context, selectedDevice, CommandQueueProperties.None, out error);

            int intPtrSize = 0;

            intPtrSize = Marshal.SizeOf(typeof(IntPtr));

            error = Cl.SetKernelArg(kernelDouble, 0, new IntPtr(intPtrSize), hDeviceMemA);

            error = Cl.SetKernelArg(kernelAdd, 0, new IntPtr(intPtrSize), hDeviceMemA);
            error = Cl.SetKernelArg(kernelAdd, 1, new IntPtr(intPtrSize), hDeviceMemB);
            error = Cl.SetKernelArg(kernelAdd, 2, new IntPtr(intPtrSize), hDeviceMemC);

            // write data from host to device
            Event clevent;

            error = Cl.EnqueueWriteBuffer(cmdQueue, hDeviceMemA, Bool.True, IntPtr.Zero,
                                          new IntPtr(1000 * sizeof(float)),
                                          A, 0, null, out clevent);
            error = Cl.EnqueueWriteBuffer(cmdQueue, hDeviceMemB, Bool.True, IntPtr.Zero,
                                          new IntPtr(1000 * sizeof(float)),
                                          B, 1, new [] { clevent }, out clevent);

            // execute kernel
            error = Cl.EnqueueNDRangeKernel(cmdQueue, kernelDouble, 1, null, new IntPtr[] { new IntPtr(1000) }, null, 1, new [] { clevent }, out clevent);


            var infoBuffer = Cl.GetEventInfo(clevent, EventInfo.CommandExecutionStatus, out var e2);

            error = Cl.EnqueueNDRangeKernel(cmdQueue, kernelAdd, 1, null, new IntPtr[] { new IntPtr(1000) }, null, 1, new [] { clevent }, out clevent);
            Console.WriteLine($"Run result: {error}");



            error = Cl.EnqueueReadBuffer(cmdQueue, hDeviceMemC, Bool.False, 0, C.Length, C, 1, new [] { clevent }, out clevent);
            Cl.WaitForEvents(1, new [] { clevent });

            for (var i = 0; i < 1000; i++)
            {
                Console.WriteLine($"[{i}]: {C[i]}");
            }

            program.Dispose();

            foreach (var res in typeof(SourceLoader).Assembly.GetManifestResourceNames())
            {
                Console.WriteLine(res);
            }
        }
 public static Context CreateContext(Device device, out ErrorCode error)
 {
     return(Cl.CreateContext(null, 1, new Device[] { device }, null, IntPtr.Zero, out error));
 }
Пример #26
0
        public static void Initialize()
        {
            Platform[] platforms = Cl.GetPlatformIDs(out ErrorCode error);
            if (error != ErrorCode.Success)
            {
                Log.Print("Impossible to run OpenCL, no any graphic platform available, abording launch.");

                Application.Exit();
            }

            Vector2I res          = Graphics.RenderResolution;
            int      pixelXAmount = res.x;
            int      pixelYAmount = res.y;

            int amountOfObjects = 1;

            unsafe
            {
                inputSize  = sizeof(C_CAMERA);
                outputSize = sizeof(byte) * pixelXAmount * pixelYAmount * 4;
            }

            UsedDevice  = Cl.GetDeviceIDs(platforms[0], DeviceType.All, out error)[0];
            gpu_context = Cl.CreateContext(null, 1, new Device[] { UsedDevice }, null, IntPtr.Zero, out error);
            InfoBuffer namebuffer = Cl.GetDeviceInfo(UsedDevice, DeviceInfo.Name, out error);

            Log.Print("OpenCL Running on " + namebuffer);

            Queue = Cl.CreateCommandQueue(gpu_context, UsedDevice, CommandQueueProperties.OutOfOrderExecModeEnable, out error);
            if (error != ErrorCode.Success)
            {
                Console.WriteLine("Impossible to create gpu queue, abording launch.");

                Application.Exit();
            }

            CLoader.LoadProjectPaths(@".\libs", new[] { "c" }, out string[] cfiles, out string[] hfiles);
            Program program = CLoader.LoadProgram(cfiles, hfiles, UsedDevice, gpu_context);

            //Program prog = CLoader.LoadProgram(CLoader.GetCFilesDir(@".\", new[] { "cl" }).ToArray(), new[] { "headers" }, UsedDevice, gpu_context);
            kernel = Cl.CreateKernel(program, "rm_render_entry", out error);

            if (error != ErrorCode.Success)
            {
                Log.Print("Error when creating kernel: " + error.ToString());
            }

            memory    = new IntPtr(outputSize);
            memInput  = (Mem)Cl.CreateBuffer(gpu_context, MemFlags.ReadOnly, inputSize, out error);
            memTime   = (Mem)(Cl.CreateBuffer(gpu_context, MemFlags.ReadOnly, timeSize, out error));
            memOutput = (Mem)Cl.CreateBuffer(gpu_context, MemFlags.WriteOnly, outputSize, out error);



            //GPU_PARAM param = new GPU_PARAM() { X_RESOLUTION = res.x, Y_RESOLUTION = res.y };

            ////Vector3D pos = camera.Malleable.Position;
            //Quaternion q = camera.Malleable.Rotation;



            IntPtr     notused;
            InfoBuffer local = new InfoBuffer(new IntPtr(4));

            error = Cl.GetKernelWorkGroupInfo(kernel, UsedDevice, KernelWorkGroupInfo.WorkGroupSize, new IntPtr(sizeof(int)), local, out notused);
            if (error != ErrorCode.Success)
            {
                Log.Print("Error getting kernel workgroup info: " + error.ToString());
            }

            //int intPtrSize = 0;
            intPtrSize = Marshal.SizeOf(typeof(IntPtr));

            Cl.SetKernelArg(kernel, 0, (IntPtr)intPtrSize, memInput);
            Cl.SetKernelArg(kernel, 1, (IntPtr)intPtrSize, memTime);

            Cl.SetKernelArg(kernel, 4, (IntPtr)intPtrSize, memOutput);

            //Cl.SetKernelArg(kernel, 2, new IntPtr(4), pixelAmount * 4);
            workGroupSizePtr = new IntPtr[] { new IntPtr(pixelXAmount * pixelYAmount) };
        }
Пример #27
0
        public static void SetupSpace(int deviceID)
        {
            //int deviceID; // will be asked to user

            List <Device> devicesList   = new List <Device>();
            List <string> deviceNames   = new List <string>();
            List <string> platformNames = new List <string>();
            int           nDevices      = 0;


            // Get list of available platforms
            Console.WriteLine("\nSearching for OpenCL-capable platforms... ");
            Platform[] platforms = Cl.GetPlatformIDs(out ClError);
            CheckErr(ClError, "CL.Setup: Cl.GetPlatformIDs");
            Console.WriteLine("{0} platforms found.\n", platforms.Length);

            foreach (Platform platform in platforms)
            {
                // Get platform info
                string platformName = Cl.GetPlatformInfo(platform, PlatformInfo.Name, out ClError).ToString();
                Console.WriteLine("Platform: " + platformName);
                CheckErr(ClError, "CL.Setup: Cl.GetPlatformInfo");

                // Get all available devices within this platform and list them on screen
                foreach (Device dev in Cl.GetDeviceIDs(platform, DeviceType.All, out ClError))
                {
                    CheckErr(ClError, "CL.Setup: Cl.GetDeviceIDs");
                    string deviceName = Cl.GetDeviceInfo(dev, DeviceInfo.Name, out ClError).ToString();
                    CheckErr(ClError, "CL.Setup: Cl.GetDeviceInfo");
                    Console.WriteLine("Device {0}: {1}", nDevices, deviceName);

                    devicesList.Add(dev);
                    deviceNames.Add(deviceName);
                    platformNames.Add(platformName);
                    nDevices++;
                }
                Console.WriteLine();
            }

            if (nDevices == 0)
            {
                throw new PlatformNotSupportedException("No OpenCL-capable platform and/or devices were found on this system.");
            }

            //Console.Write("Enter ID of device to use: ");
            //deviceID = int.Parse(Console.ReadLine());

            // Select device according to user's choice
            device = devicesList[deviceID];
            Console.WriteLine("\nUsing device {0}", deviceNames[deviceID]);

            // Create OpenCL context
            context = Cl.CreateContext(null, 1, new[] { device }, ContextNotify, IntPtr.Zero, out ClError);    //Second parameter is amount of devices
            CheckErr(ClError, "CL.Setup: Cl.CreateContext");

            // Create OpenCL command queue
            queue = Cl.CreateCommandQueue(context, device, (CommandQueueProperties)0, out ClError);
            CheckErr(ClError, "CL.Setup: Cl.CreateCommandQueue");

            // Extract some device info
            maxWorkItemSizes = Cl.GetDeviceInfo(device, DeviceInfo.MaxWorkItemSizes, out ClError).CastToEnumerable <int>(new int[] { 0, 1, 2 }).ToList();
            Console.WriteLine("Max work item sizes: {0}, {1}, {2}", maxWorkItemSizes[0], maxWorkItemSizes[1], maxWorkItemSizes[2]);

            maxWorkGroupSize = Cl.GetDeviceInfo(device, DeviceInfo.MaxWorkGroupSize, out ClError).CastTo <int>();
            Console.WriteLine("Max work group size: {0}", maxWorkGroupSize);

            maxComputeUnits = Cl.GetDeviceInfo(device, DeviceInfo.MaxComputeUnits, out ClError).CastTo <int>();
            Console.WriteLine("Max compute units: {0}", maxComputeUnits);
        }
Пример #28
0
        public Context(Dictionary <IntPtr, IntPtr> properties, Device[] devices, Action <string, byte[], object> notify, object user_data)
            : this()
        {
            if (devices == null)
            {
                throw new ArgumentNullException("devices");
            }

            unsafe
            {
                IntPtr *device_ptrs = stackalloc IntPtr[devices.Length];

                for (int i = 0; i < devices.Length; ++i)
                {
                    device_ptrs[i] = devices[i].Handle;
                }

                int property_count = properties == null ? 0 : properties.Count;

                IntPtr *properties_ptr = stackalloc IntPtr[property_count * 2 + 1];

                int index = 0;
                if (properties != null)
                {
                    foreach (var pair in properties)
                    {
                        properties_ptr[index++] = pair.Key;
                        properties_ptr[index++] = pair.Value;
                    }
                    properties_ptr[index] = IntPtr.Zero;
                }
                else
                {
                    properties_ptr = null;
                }

                var function_ptr = IntPtr.Zero;
                var data_handle  = new GCHandle();
                var data_ptr     = IntPtr.Zero;

                if (notify != null)
                {
                    var data = Tuple.Create(notify, user_data);
                    data_handle = GCHandle.Alloc(data);
                    data_ptr    = GCHandle.ToIntPtr(data_handle);

                    function_ptr = Marshal.GetFunctionPointerForDelegate(new CallbackDelegete(Callback));
                }

                try
                {
                    int errcode = 0;
                    Handle = Cl.CreateContext(properties_ptr, (uint)devices.Length, device_ptrs,
                                              function_ptr, data_ptr.ToPointer(), &errcode);
                    ClHelper.GetError(errcode);

                    CallbackPointers.Add(Handle, data_handle);
                }
                catch (Exception)
                {
                    if (data_handle.IsAllocated)
                    {
                        data_handle.Free();
                    }
                    throw;
                }
            }
        }
Пример #29
0
 public unsafe Context CreateContext()
 {
     return(new Context(Cl.CreateContext(null, 1, new[] { this }, null, IntPtr.Zero, out ErrorCode _)));
 }
Пример #30
0
        private void init(string oclProgramSourcePath)
        {
            string kernelSource = File.ReadAllText(oclProgramSourcePath);

            string[] kernelNames = new string[] { "accumulate", "quickBlurImgH", "quickBlurImgV", "upsizeImg", "halfSizeImgH", "halfSizeImgV", "getLumaImg", "mapToGreyscaleBmp", "getContrastImg", "capHolesImg", "maxReduceImgH", "maxReduceImgV", "mapToFauxColorsBmp", "quickSpikesFilterImg", "convolveImg" };

            bool gpu = true;

            //err = clGetDeviceIDs(NULL, gpu ? CL_DEVICE_TYPE_GPU : CL_DEVICE_TYPE_CPU, 1, &device_id, NULL);
            // NVidia driver doesn't seem to support a NULL first param (properties)
            // http://stackoverflow.com/questions/19140989/how-to-remove-cl-invalid-platform-error-in-opencl-code

            // now get all the platform IDs
            Platform[] platforms = Cl.GetPlatformIDs(out err);
            assert(err, "Error: Failed to get platform ids!");

            InfoBuffer deviceInfo = Cl.GetPlatformInfo(platforms[0], PlatformInfo.Name, out err);

            assert(err, "error retrieving platform name");
            Console.WriteLine("Platform name: {0}\n", deviceInfo.ToString());


            //                                 Arbitrary, should be configurable
            Device[] devices = Cl.GetDeviceIDs(platforms[0], gpu ? DeviceType.Gpu : DeviceType.Cpu, out err);
            assert(err, "Error: Failed to create a device group!");

            _device = devices[0]; // Arbitrary, should be configurable

            deviceInfo = Cl.GetDeviceInfo(_device, DeviceInfo.Name, out err);
            assert(err, "error retrieving device name");
            Debug.WriteLine("Device name: {0}", deviceInfo.ToString());

            deviceInfo = Cl.GetDeviceInfo(_device, DeviceInfo.ImageSupport, out err);
            assert(err, "error retrieving device image capability");
            Debug.WriteLine("Device supports img: {0}", (deviceInfo.CastTo <Bool>() == Bool.True));

            // Create a compute context
            //
            _context = Cl.CreateContext(null, 1, new[] { _device }, ContextNotify, IntPtr.Zero, out err);
            assert(err, "Error: Failed to create a compute context!");

            // Create the compute program from the source buffer
            //
            _program = Cl.CreateProgramWithSource(_context, 1, new[] { kernelSource }, new[] { (IntPtr)kernelSource.Length }, out err);
            assert(err, "Error: Failed to create compute program!");

            // Build the program executable
            //
            err = Cl.BuildProgram(_program, 1, new[] { _device }, string.Empty, null, IntPtr.Zero);
            assert(err, "Error: Failed to build program executable!");
            InfoBuffer buffer = Cl.GetProgramBuildInfo(_program, _device, ProgramBuildInfo.Log, out err);

            Debug.WriteLine("build success: {0}", buffer.CastTo <BuildStatus>() == BuildStatus.Success);

            foreach (string kernelName in kernelNames)
            {
                // Create the compute kernel in the program we wish to run
                //
                OpenCL.Net.Kernel kernel = Cl.CreateKernel(_program, kernelName, out err);
                assert(err, "Error: Failed to create compute kernel!");
                _kernels.Add(kernelName, kernel);
            }

            // Create a command queue
            //
            _commandsQueue = Cl.CreateCommandQueue(_context, _device, CommandQueueProperties.None, out err);
            assert(err, "Error: Failed to create a command commands!");
        }