Beispiel #1
0
        static void Main(string[] args)
        {
            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);
            string firstKernel = string.Empty;

            foreach (Platform 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: {0}", buffer);
                    firstKernel = buffer.ToString();
                }
            }
            var basePath    = AppDomain.CurrentDomain.BaseDirectory;
            var filePath    = Path.Combine(basePath, @"TestKernels\TestKernel1.cl");
            var tasksKernel = new OpenCL.Net.Tasks.Kernel();
            var environment = firstKernel.CreateCLEnvironment();

            tasksKernel.Execute();
        }
Beispiel #2
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);
        }
        private Kernel CompileKernel(string kernelName)
        {
            ErrorCode error;

            if (!File.Exists(PROGRAM_PATH))
            {
                throw new IOException("Program does not exist at path.");
            }

            string programSource = File.ReadAllText(PROGRAM_PATH);

            using (Program program = Cl.CreateProgramWithSource(context, 1, new[] { programSource }, null, out error))
            {
                CheckErr(error, "Cl.CreateProgramWithSource");

                //Compile kernel source
                error = Cl.BuildProgram(program, 1, new[] { device }, "-Werror", null, IntPtr.Zero);
                InfoBuffer log = Cl.GetProgramBuildInfo(program, device, ProgramBuildInfo.Log, out error);
                Console.WriteLine(log);
                CheckErr(error, "Cl.BuildProgram");

                //Check for any compilation errors
                if (Cl.GetProgramBuildInfo(program, device, ProgramBuildInfo.Status, out error).CastTo <BuildStatus>() != BuildStatus.Success)
                {
                    CheckErr(error, "Cl.GetProgramBuildInfo");
                }

                //Create the required kernel (entry function)
                Kernel kernel = Cl.CreateKernel(program, kernelName, out error);
                CheckErr(error, "Cl.CreateKernel");

                return(kernel);
            }
        }
Beispiel #4
0
        public void PlatformQueries()
        {
            uint      platformCount;
            ErrorCode result = Cl.GetPlatformIDs(0, null, out platformCount);

            Assert.AreEqual(result, ErrorCode.Success, "Could not get platform count");
            Console.WriteLine("{0} platforms found", platformCount);

            var platformIds = new Platform[platformCount];

            result = Cl.GetPlatformIDs(platformCount, platformIds, out platformCount);
            Assert.AreEqual(result, ErrorCode.Success, "Could not get platform ids");

            foreach (Platform platformId in platformIds)
            {
                IntPtr paramSize;
                result = Cl.GetPlatformInfo(platformId, PlatformInfo.Name, IntPtr.Zero, InfoBuffer.Empty, out paramSize);
                Assert.AreEqual(result, ErrorCode.Success, "Could not get platform name size");

                using (var buffer = new InfoBuffer(paramSize))
                {
                    result = Cl.GetPlatformInfo(platformIds[0], PlatformInfo.Name, paramSize, buffer, out paramSize);
                    Assert.AreEqual(result, ErrorCode.Success, "Could not get platform name string");

                    Console.WriteLine("Platform: {0}", buffer);
                }
            }
        }
Beispiel #5
0
        public void PlatformQueries()
        {
            uint platformCount;
            ErrorCode result = Cl.GetPlatformIDs(0, null, out platformCount);
            Assert.AreEqual(result, ErrorCode.Success, "Could not get platform count");
            Console.WriteLine("{0} platforms found", platformCount);

            var platformIds = new Platform[platformCount];
            result = Cl.GetPlatformIDs(platformCount, platformIds, out platformCount);
            Assert.AreEqual(result, ErrorCode.Success, "Could not get platform ids");

            foreach (Platform platformId in platformIds)
            {
                IntPtr paramSize;
                result = Cl.GetPlatformInfo(platformId, PlatformInfo.Name, IntPtr.Zero, InfoBuffer.Empty, out paramSize);
                Assert.AreEqual(result, ErrorCode.Success, "Could not get platform name size");

                using (var buffer = new InfoBuffer(paramSize))
                {
                    result = Cl.GetPlatformInfo(platformIds[0], PlatformInfo.Name, paramSize, buffer, out paramSize);
                    Assert.AreEqual(result, ErrorCode.Success, "Could not get platform name string");

                    Console.WriteLine("Platform: {0}", buffer);
                }
            }
        }
Beispiel #6
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")
        }
Beispiel #7
0
        public static IList <DeviceOption> EnumerateDevices(Platform platform, DeviceType deviceType = DeviceType.All)
        {
            uint deviceCount;
            var  result  = Cl.GetDeviceIDs(platform, deviceType, 0, null, out deviceCount);
            var  devices = new Device[deviceCount];

            result = Cl.GetDeviceIDs(platform, deviceType, deviceCount, devices, out var numberDevices);

            var deviceList = new List <DeviceOption>();

            foreach (var device in devices)
            {
                IntPtr paramSize;
                result = Cl.GetDeviceInfo(device, DeviceInfo.Name, IntPtr.Zero, InfoBuffer.Empty, out paramSize);

                string name = "";
                using (var buffer = new InfoBuffer(paramSize))
                {
                    result = Cl.GetDeviceInfo(device, DeviceInfo.Name, paramSize, buffer, out paramSize);
                    name   = buffer.ToString();
                }

                deviceList.Add(new DeviceOption(device, name));
            }
            return(deviceList);
        }
Beispiel #8
0
        public static IList <PlatformOption> EnumeratePlatforms()
        {
            uint      platformCount;
            ErrorCode result = Cl.GetPlatformIDs(0, null, out platformCount);
            // Load platform ids.
            var platforms = new Platform[platformCount];

            result = Cl.GetPlatformIDs(platformCount, platforms, out platformCount);
            var platformList = new List <PlatformOption>();

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

                string name = "";
                using (var buffer = new InfoBuffer(paramSize))
                {
                    result = Cl.GetPlatformInfo(platform, PlatformInfo.Name, paramSize, buffer, out paramSize);
                    name   = buffer.ToString();
                }

                platformList.Add(new PlatformOption(platform, name));
            }
            return(platformList);
        }
Beispiel #9
0
 public InfoBufferArray(int length)
 {
     _buffers = new IntPtr[length];
     for (int i = 0; i < length; i++)
     {
         _buffers[i] = new InfoBuffer(size).Address;
     }
 }
 public static OpenCLErrorCode GetContextInfo(ContextHandle context,
                                        ContextInfo paramName,
                                        IntPtr paramValueSize,
                                        InfoBuffer paramValue,
                                        out IntPtr paramValueSizeRet)
 {
     return clGetContextInfo((context as IHandleData).Handle, paramName, paramValueSize, paramValue.Address, out paramValueSizeRet);
 }
Beispiel #11
0
 private void Start()
 {
     infoBuffer  = this.GetComponent <InfoBuffer>();
     colorBuffer = GetComponent <Renderer>().material.color;
     rigidBody   = this.GetComponent <Rigidbody>();
     this.GetComponent <InfoBuffer>().lastplaceGrounded = this.transform.position;
     breathOvertime += breathTime;
 }
 /// <summary>
 /// Get Information for a Device (CPU/GPU/...)
 /// </summary>
 /// <returns></returns>
 public static OpenCLErrorCode GetDeviceInfo(DeviceHandle device,
                                       DeviceInfo paramName,
                                       IntPtr paramValueSize,
                                       InfoBuffer paramValue,
                                       out IntPtr paramValueSizeRet)
 {
     return clGetDeviceInfo((device as IHandleData).Handle, paramName, paramValueSize, paramValue.Address, out paramValueSizeRet);
 }
 /// <summary>
 /// Returns Information about a specific Platform
 /// </summary>
 /// <returns></returns>
 public static OpenCLErrorCode GetPlatformInfo(PlatformHandle platformId,
                                         PlatformInfo paramName,
                                         IntPtr paramValueBufferSize,
                                         InfoBuffer paramValue,
                                         out IntPtr paramValueSize)
 {
     return clGetPlatformInfo((platformId as IHandleData).Handle, paramName, paramValueBufferSize, paramValue.Address, out paramValueSize);
 }
Beispiel #14
0
 /// <summary>
 /// Creates all potential kernels in program
 /// </summary>
 public void CreateAllKernels()
 {
     Kernel[] kernels = Cl.CreateKernelsInProgram(_program, out _error);
     CLException.CheckException(_error);
     for (int i = 0; i < kernels.Length; i++)
     {
         InfoBuffer name = Cl.GetKernelInfo(kernels[i], KernelInfo.FunctionName, out _error);
         _kernels.Add(name.ToString(), kernels[i]);
     }
 }
Beispiel #15
0
 private void setDynamicReferences()
 {
     infoBuffer.isNoisy    = !isSneaking;
     infoBuffer.isInCover  = isInCover;
     infoBuffer.isGrounded = grounded;
     this.GetComponent <PlayerSettings>().isGrabbable  = isGrabbable;
     this.GetComponent <PlayerSettings>().grabRange    = grabRange;
     this.GetComponent <PlayerSettings>().playerHeight = playerHeight;
     isBoosting = this.GetComponent <InfoBuffer>().isBoosting;
     infoBuffer = this.GetComponent <InfoBuffer>();
 }
Beispiel #16
0
 //IK ANIMATION TARGETING REQUIRES EXTRACTION OF IK MOVEMENT
 #region Constructor
 public PickUp(GameObject OwnerObject, IKRef IKRef, InfoBuffer InfoBuffer, LayerMask GrabbableLayer, float grabRange, float playerHeight, float animTime)
 {
     this.ownerObject    = OwnerObject;
     this.ownerTransform = OwnerObject.transform;
     this.iKRef          = IKRef;
     this.infoBuffer     = InfoBuffer;
     this.grabRange      = grabRange;
     this.playerHeight   = playerHeight;
     this.animTime       = animTime;
     this.isHolding      = InfoBuffer.isHolding;
     this.isHeldOverhead = InfoBuffer.isHeldOverhead;
     this.grabObject     = infoBuffer.grabObject;
     //It would be more swift to put player settings into their own monobehavior so that we could call a transform, and IK ref, an InfoBuffer, and a PlayerSettings, rather than 6 things calling 3 would be better.
 }
Beispiel #17
0
 /// <summary>
 /// Builds Program
 /// </summary>
 public void BuildProgram()
 {
     try
     {
         _error = Cl.BuildProgram(_program, 0, null, null, null, IntPtr.Zero);
         CLException.CheckException(_error);
     }
     catch (CLException)
     {
         Console.WriteLine("Could not build program!");
         InfoBuffer buildLog = Cl.GetProgramBuildInfo(_program, _handle.Device, ProgramBuildInfo.Log, out _error);
         CLException.CheckException(_error);
         Console.WriteLine("Build Log: " + buildLog.ToString());
     }
 }
        public static InfoBuffer GetMemObjectInfo(IMem mem, MemInfo paramName, out ErrorCode error)
        {
            if (paramName == MemInfo.HostPtr) // Handle special case
            {
                IntPtr size   = GetInfo(Cl.GetMemObjectInfo, mem, MemInfo.Size, out error).CastTo <IntPtr>();
                var    buffer = new InfoBuffer(size);
                error = GetMemObjectInfo(mem, paramName, size, buffer, out size);
                if (error != ErrorCode.Success)
                {
                    return(InfoBuffer.Empty);
                }

                return(buffer);
            }

            return(GetInfo(GetMemObjectInfo, mem, paramName, out error));
        }
        internal static InfoBuffer GetInfo <THandle1Type, THandle2Type, TEnumType>(
            GetInfoDelegate <THandle1Type, THandle2Type, TEnumType> method, THandle1Type handle1, THandle2Type handle2, TEnumType name, out ErrorCode error)
        {
            IntPtr paramSize;

            error = method(handle1, handle2, name, IntPtr.Zero, InfoBuffer.Empty, out paramSize);
            // no error checking here because some implementations return InvalidValue even
            // though the paramSize is correctly returned

            var buffer = new InfoBuffer(paramSize);

            error = method(handle1, handle2, name, paramSize, buffer, out paramSize);
            if (error != ErrorCode.Success)
            {
                return(InfoBuffer.Empty);
            }

            return(buffer);
        }
Beispiel #20
0
        public void DeviceQueries()
        {
            uint      platformCount;
            ErrorCode result = Cl.GetPlatformIDs(0, null, out platformCount);

            Assert.AreEqual(result, ErrorCode.Success, "Could not get platform count");
            Console.WriteLine("{0} platforms found", platformCount);

            var platformIds = new Platform[platformCount];

            result = Cl.GetPlatformIDs(platformCount, platformIds, out platformCount);
            Assert.AreEqual(result, ErrorCode.Success, "Could not get platform ids");

            foreach (Platform platformId in platformIds)
            {
                IntPtr paramSize;
                result = Cl.GetPlatformInfo(platformId, PlatformInfo.Name, IntPtr.Zero, InfoBuffer.Empty, out paramSize);
                Assert.AreEqual(result, ErrorCode.Success, "Could not get platform name size");

                using (var buffer = new InfoBuffer(paramSize))
                {
                    result = Cl.GetPlatformInfo(platformIds[0], PlatformInfo.Name, paramSize, buffer, out paramSize);
                    Assert.AreEqual(result, ErrorCode.Success, "Could not get platform name string");
                }

                uint deviceCount;
                result = Cl.GetDeviceIDs(platformIds[0], DeviceType.All, 0, null, out deviceCount);
                Assert.AreEqual(result, ErrorCode.Success, "Could not get device count");

                var deviceIds = new Device[deviceCount];
                result = Cl.GetDeviceIDs(platformIds[0], DeviceType.All, deviceCount, deviceIds, out deviceCount);
                Assert.AreEqual(result, ErrorCode.Success, "Could not get device ids");

                result = Cl.GetDeviceInfo(deviceIds[0], DeviceInfo.Vendor, IntPtr.Zero, InfoBuffer.Empty, out paramSize);
                Assert.AreEqual(result, ErrorCode.Success, "Could not get device vendor name size");
                using (var buf = new InfoBuffer(paramSize))
                {
                    result = Cl.GetDeviceInfo(deviceIds[0], DeviceInfo.Vendor, paramSize, buf, out paramSize);
                    Assert.AreEqual(result, ErrorCode.Success, "Could not get device vendor name string");
                    var deviceVendor = buf.ToString();
                }
            }
        }
        public static string GetPlatformInfo(this Platform inPlatform, PlatformInfo inPlatformInfo)
        {
            IntPtr paramSize;
            var tmpErrorCode = OpenCL_PlatformInformation.GetPlatformInfo(inPlatform.Handle, inPlatformInfo, IntPtr.Zero, InfoBuffer.Empty, out paramSize);
            if (tmpErrorCode != OpenCLErrorCode.Success)
            {
                Log.Add(LogType.Warning, $"Could not get platform name size: {tmpErrorCode}");
                return " ";
            }

            using (var buffer = new InfoBuffer(paramSize))
            {
                tmpErrorCode = OpenCL_PlatformInformation.GetPlatformInfo(inPlatform.Handle, inPlatformInfo, paramSize, buffer, out paramSize);

                Log.Add(LogType.Info, $"Platform: {buffer}");

                return buffer.ToString();
            }
        }
        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);
        }
Beispiel #23
0
        public static InfoBuffer GetMemObjectInfo(Mem mem, MemInfo paramName, out ErrorCode error)
        {
            if (paramName == MemInfo.HostPtr) // Handle special case
            {
                IntPtr size = GetInfo(Cl.GetMemObjectInfo, mem, Cl.MemInfo.Size, out error).CastTo<IntPtr>();
                var buffer = new InfoBuffer(size);
                error = GetMemObjectInfo(mem, paramName, size, buffer, out size);
                if (error != ErrorCode.Success)
                    return InfoBuffer.Empty;

                return buffer;
            }

            return GetInfo(GetMemObjectInfo, mem, paramName, out error);
        }
Beispiel #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);
            }
        }
Beispiel #25
0
        public void DeviceQueries()
        {
            uint platformCount;
            ErrorCode result = Cl.GetPlatformIDs(0, null, out platformCount);
            Assert.AreEqual(result, ErrorCode.Success, "Could not get platform count");
            Console.WriteLine("{0} platforms found", platformCount);

            var platformIds = new Platform[platformCount];
            result = Cl.GetPlatformIDs(platformCount, platformIds, out platformCount);
            Assert.AreEqual(result, ErrorCode.Success, "Could not get platform ids");

            foreach (Platform platformId in platformIds)
            {
                IntPtr paramSize;
                result = Cl.GetPlatformInfo(platformId, PlatformInfo.Name, IntPtr.Zero, InfoBuffer.Empty, out paramSize);
                Assert.AreEqual(result, ErrorCode.Success, "Could not get platform name size");

                using (var buffer = new InfoBuffer(paramSize))
                {
                    result = Cl.GetPlatformInfo(platformIds[0], PlatformInfo.Name, paramSize, buffer, out paramSize);
                    Assert.AreEqual(result, ErrorCode.Success, "Could not get platform name string");
                }

                uint deviceCount;
                result = Cl.GetDeviceIDs(platformIds[0], DeviceType.All, 0, null, out deviceCount);
                Assert.AreEqual(result, ErrorCode.Success, "Could not get device count");

                var deviceIds = new Device[deviceCount];
                result = Cl.GetDeviceIDs(platformIds[0], DeviceType.All, deviceCount, deviceIds, out deviceCount);
                Assert.AreEqual(result, ErrorCode.Success, "Could not get device ids");

                result = Cl.GetDeviceInfo(deviceIds[0], DeviceInfo.Vendor, IntPtr.Zero, InfoBuffer.Empty, out paramSize);
                Assert.AreEqual(result, ErrorCode.Success, "Could not get device vendor name size");
                using (var buf = new InfoBuffer(paramSize))
                {
                    result = Cl.GetDeviceInfo(deviceIds[0], DeviceInfo.Vendor, paramSize, buf, out paramSize);
                    Assert.AreEqual(result, ErrorCode.Success, "Could not get device vendor name string");
                    var deviceVendor = buf.ToString();
                }
            }
        }
 public static OpenCLErrorCode GetMemObjectInfo(IMemoryObject memObj,
                                          MemInfo paramName,
                                          IntPtr paramValueSize,
                                          InfoBuffer paramValue,
                                          out IntPtr paramValueSizeRet)
 {
     return clGetMemObjectInfo((memObj as IHandleData).Handle, paramName, paramValueSize, paramValue.Address, out paramValueSizeRet);
 }
Beispiel #27
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) };
        }
        public void SquareArray()
        {
            // Adapted from
            //https://github.com/rsnemmen/OpenCL-examples/blob/master/square_array/square.cl
            int array_size = 100000;
            var bytes      = (IntPtr)(array_size * sizeof(float));

            var hdata   = new float[array_size];
            var houtput = new float[array_size];

            for (int i = 0; i < array_size; i++)
            {
                hdata[i] = 1.0f * i;
            }

            ErrorCode error;
            Device    device = (from d 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 d).First();

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

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

            using (Program program = Cl.CreateProgramWithSource(context, 1, new[] { source }, null, out error))
            {
                Assert.AreEqual(error, ErrorCode.Success);
                error = Cl.BuildProgram(program, 1, new[] { device }, string.Empty, null, IntPtr.Zero);
                Assert.AreEqual(ErrorCode.Success, error);
                Assert.AreEqual(Cl.GetProgramBuildInfo(program, device, ProgramBuildInfo.Status, out error).CastTo <BuildStatus>(), BuildStatus.Success);

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

                CommandQueue cmdQueue = Cl.CreateCommandQueue(context, device, (CommandQueueProperties)0, out error);

                IMem ddata   = Cl.CreateBuffer(context, MemFlags.ReadOnly, bytes, null, out error);
                IMem doutput = Cl.CreateBuffer(context, MemFlags.WriteOnly, bytes, null, out error);

                error = Cl.EnqueueWriteBuffer(cmdQueue, ddata, Bool.True, (IntPtr)0, bytes, hdata, 0, null, out Event clevent);
                Assert.AreEqual(ErrorCode.Success, error);

                error  = Cl.SetKernelArg(kernel, 0, new IntPtr(Marshal.SizeOf(typeof(IntPtr))), ddata);
                error |= Cl.SetKernelArg(kernel, 1, new IntPtr(Marshal.SizeOf(typeof(IntPtr))), doutput);
                error |= Cl.SetKernelArg(kernel, 2, new IntPtr(Marshal.SizeOf(typeof(int))), new IntPtr(array_size));
                Assert.AreEqual(error, ErrorCode.Success);

                int local_size  = 256;
                var infoBufferr = new InfoBuffer();
                error = Cl.GetKernelWorkGroupInfo(kernel, device, KernelWorkGroupInfo.WorkGroupSize, new IntPtr(sizeof(int)), new InfoBuffer(), out IntPtr localSize);
                var x           = localSize.ToInt32();//Why is it giving me 8??? Vega 56 has 256 work group size
                int global_size = (int)Math.Ceiling(array_size / (float)local_size) * local_size;

                error = Cl.EnqueueNDRangeKernel(cmdQueue, kernel, 1, null, new IntPtr[] { new IntPtr(global_size) }, new IntPtr[] { new IntPtr(local_size) }, 0, null, out clevent);
                Cl.Finish(cmdQueue);
                Cl.EnqueueReadBuffer(cmdQueue, doutput, Bool.True, IntPtr.Zero, bytes, houtput, 0, null, out clevent);
                houtput.ForEach(o => Console.Write($"{o}, "));


                Cl.ReleaseKernel(kernel);
                Cl.ReleaseMemObject(ddata);
                Cl.ReleaseMemObject(doutput);
                Cl.ReleaseCommandQueue(cmdQueue);
                Cl.ReleaseProgram(program);
                Cl.ReleaseContext(context);
            }
        }
        public void TestSlimeFinder()
        {
            const int squareLength = 1024;
            int       globalSize   = squareLength * squareLength;
            var       candidates   = new int[globalSize];

            ErrorCode error;
            Device    device = (from d 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 d).First();

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

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

            using Program 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);

            Assert.AreEqual(buildStatus.CastTo <BuildStatus>(), BuildStatus.Success);
            Assert.AreEqual(error, ErrorCode.Success);

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

            Assert.AreEqual(error, ErrorCode.Success);

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

            Assert.AreEqual(error, ErrorCode.Success);

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

            Assert.AreEqual(error, ErrorCode.Success);

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

            error  = Cl.SetKernelArg(kernel, 0, intSizePtr, new IntPtr(0));
            error |= Cl.SetKernelArg(kernel, 1, intSizePtr, new IntPtr(0));
            error |= Cl.SetKernelArg(kernel, 2, new IntPtr(Marshal.SizeOf(typeof(IntPtr))), dataOut);
            error |= Cl.SetKernelArg(kernel, 3, intSizePtr, new IntPtr(420));
            error |= Cl.SetKernelArg(kernel, 4, intSizePtr, new IntPtr(globalSize));
            Assert.AreEqual(error, ErrorCode.Success);

            int local_size  = 256;
            int global_size = (int)Math.Ceiling(globalSize / (float)local_size) * local_size;
            var stopW       = new Stopwatch();

            stopW.Start();
            error = Cl.EnqueueNDRangeKernel(queue, kernel, 1, null, new IntPtr[] { new IntPtr(global_size) }, new IntPtr[] { new IntPtr(local_size) }, 0, null, out Event clevent);
            Assert.AreEqual(error, ErrorCode.Success);

            Cl.Finish(queue);
            stopW.Stop();


            Cl.EnqueueReadBuffer(queue, dataOut, Bool.True, IntPtr.Zero, (IntPtr)(globalSize * sizeof(int)), candidates, 0, null, out clevent);
            candidates.ForEach(c =>
            {
                if (c > 50)
                {
                    Console.Write($"{c},");
                }
            });

            Console.WriteLine($"\n{stopW.ElapsedMilliseconds} ms");


            error  = Cl.SetKernelArg(kernel, 0, intSizePtr, new IntPtr(16383));
            error |= Cl.SetKernelArg(kernel, 1, intSizePtr, new IntPtr(16383));

            stopW.Start();
            error = Cl.EnqueueNDRangeKernel(queue, kernel, 1, null, new IntPtr[] { new IntPtr(global_size) }, new IntPtr[] { new IntPtr(local_size) }, 0, null, out clevent);
            Assert.AreEqual(error, ErrorCode.Success);

            Cl.Finish(queue);
            stopW.Stop();


            Cl.EnqueueReadBuffer(queue, dataOut, Bool.True, IntPtr.Zero, (IntPtr)(globalSize * sizeof(int)), candidates, 0, null, out clevent);
            candidates.ForEach(c =>
            {
                if (c > 50)
                {
                    Console.Write($"{c},");
                }
            });

            Console.WriteLine($"\n{stopW.ElapsedMilliseconds} ms");

            Cl.ReleaseKernel(kernel);
            Cl.ReleaseMemObject(dataOut);
            Cl.ReleaseCommandQueue(queue);
            Cl.ReleaseProgram(program);
            Cl.ReleaseContext(context);
        }
        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!");
        }