Exemplo n.º 1
0
        public KernelManager(GraphicsInterop interop, InputManager input, string source)
        {
            _input = input;
            var localSizeSingle = (long)Math.Sqrt(interop.Device.MaxWorkGroupSize);

            _localSize = new[] { localSizeSingle, localSizeSingle };
            //_localSize = new[] { interop.Device.MaxWorkGroupSize, 1 };

            _program = new ComputeProgram(interop.Context, source);
            try
            {
                _program.Build(new[] { interop.Device }, "", null, IntPtr.Zero);
            }
            catch (InvalidBinaryComputeException)
            {
                Console.WriteLine(_program.GetBuildLog(interop.Device));
                return;
            }
            catch (BuildProgramFailureComputeException)
            {
                Console.WriteLine(_program.GetBuildLog(interop.Device));
                return;
            }
            Console.WriteLine(_program.GetBuildLog(interop.Device));
            _kernels = _program.CreateAllKernels().ToArray();
        }
Exemplo n.º 2
0
        public void SetKernel(string OpenCLBody, string EntryPoint)
        {
            this.OpenCLBody = OpenCLBody;
            this.EntryPoint = EntryPoint;
            ComputeProgram program = new ComputeProgram(context, OpenCLBody);

            try
            {
                program.Build(null, null, null, IntPtr.Zero);
                kernel = program.CreateKernel(EntryPoint);
            }
            catch (BuildProgramFailureComputeException)
            {
                string message = program.GetBuildLog(Accelerator.Device);
                throw new ArgumentException(message);
            }
            catch (ComputeException)
            {
                string message = program.GetBuildLog(Accelerator.Device);
                throw new ArgumentException(message);
            }

            MethodInfo = new CLMethod(EntryPoint, OpenCLBody);
            MethodSet  = true;
        }
Exemplo n.º 3
0
        //Initializing everything OpenGL related
        public void OpenGLInit()
        {
            ComputePlatform platform = null;
            ComputeDevice   device   = null;

            for (int p = 0; p < ComputePlatform.Platforms.Count; ++p)
            {
                platform = ComputePlatform.Platforms[p];

                /*Console.WriteLine
                 * ("Platform {0} \"{1}\" has {2} devices attached"
                 * , p
                 * , platform.Name
                 * , platform.Devices.Count);*/

                for (int d = 0; d < platform.Devices.Count; d++)
                {
                    device = platform.Devices[d];
                    //Console.WriteLine("  device [{0}]: {1}", d, device.Name);
                }
            }

            context = new ComputeContext(
                ComputeDeviceTypes.Gpu,
                new ComputeContextPropertyList(platform),
                null,
                IntPtr.Zero);

            queue = new ComputeCommandQueue
                        (context
                        , device
                        , ComputeCommandQueueFlags.Profiling // enable event timing
                        );

            StreamReader reader = new StreamReader("../../GameOfLife.cl");
            string       source = reader.ReadToEnd();

            reader.Close();
            //Console.WriteLine(source);

            program = new ComputeProgram(context, source);
            try
            {
                program.Build(null, null, null, IntPtr.Zero);
            }
            catch
            {
                Console.WriteLine(program.GetBuildLog(device));   // error log
                System.Environment.Exit(7);
            }
            Console.WriteLine(program.GetBuildLog(device));     // warnings
        }
Exemplo n.º 4
0
        public override void Init(WaveFormat AFormat)
        {
            base.Init(AFormat);

            try
            {
                FDevice  = App.Settings.Preferences.OpenCL.GetComputeDevice();
                FContext = new ComputeContext(new ComputeDevice[] { FDevice }, new ComputeContextPropertyList(FDevice.Platform), null, IntPtr.Zero);

                program = new ComputeProgram(FContext, FProgramSource);

                program.Build(new[] { FDevice }, null, null, IntPtr.Zero);

                kernel   = program.CreateKernel("Wave");
                commands = new ComputeCommandQueue(FContext, FContext.Devices[0], ComputeCommandQueueFlags.None);
            }
            catch (BuildProgramFailureComputeException bex)
            {
                Debug.WriteLine(bex.Message);
                Debug.WriteLine(program.GetBuildLog(FDevice));
                throw;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
Exemplo n.º 5
0
        public static ComputeProgram CreateProgram(string source)
        {
            string realType = Marshal.SizeOf(typeof(Real)) == Marshal.SizeOf(typeof(double)) ? "double" : "float";

            //for precision setting of floating point
            source = REAL_HEADER_STRING + source;

            //Add at double precision
            if (realType == "double")
            {
                source = USE_DOUBLE_HEADER_STRING + source;
            }

            ComputeProgram program = new ComputeProgram(Context, source);

            try
            {
                program.Build(Devices, string.Format("-D REAL={0} -Werror", realType), null, IntPtr.Zero);
            }
            catch
            {
                MessageBox.Show(program.GetBuildLog(Devices[DeviceIndex]));
            }

            return(program);
        }
Exemplo n.º 6
0
        public TFP Hello(float num)
        {
            ComputeBuffer <TFP> result = new ComputeBuffer <TFP>(context, ComputeMemoryFlags.WriteOnly, 1);
            string source = Encoding.ASCII.GetString(FZYK.Nest.Properties.Resources.nest);

            if (fpType == FPType.FP64AMD)
            {
                source = "#define AMDFP64\n" + source;
            }
            else if (fpType == FPType.FP64)
            {
                source = "#define FP64\n" + source;
            }
            ComputeProgram program = new ComputeProgram(context, source);

            try
            {
                program.Build(null, null, null, IntPtr.Zero);
            }
            catch (Exception)
            {
                var log = program.GetBuildLog(context.Devices[0]);
                Debugger.Break();
            }

            ComputeKernel kernel = program.CreateKernel("hello");

            TFP[] myresult = RunKernalTest(num, result, kernel);
            return(myresult[0]);
        }
Exemplo n.º 7
0
        public static ComputeProgram CreateProgram(string source)
        {
            string realType = Real.Size == sizeof(double) ? "double" : "float";

            //浮動小数点の精度設定用
            source = REAL_HEADER_STRING + source;

            //倍精度時に追加
            if (realType == "double")
            {
                source = USE_DOUBLE_HEADER_STRING + source;
            }

            ComputeProgram program = new ComputeProgram(Context, source);

            try
            {
                program.Build(ComputePlatform.Platforms[PlatformId].Devices, string.Format("-D REAL={0} -Werror", realType), null, IntPtr.Zero);
            }
            catch (Exception e)
            {
                throw new Exception(program.GetBuildLog(ComputePlatform.Platforms[PlatformId].Devices[DeviceIndex]), e);
            }

            return(program);
        }
Exemplo n.º 8
0
        public void SetDevice(int deviceIndx)
        {
            if ((deviceIndx < 0) || (deviceIndx >= oclDevices.Count))
            {
                throw new IndexOutOfRangeException("Invalid OpenCL device index.");
            }

            if (oclContext != null)
            {
                oclContext.Dispose();
                oclContext = null;
            }

            if (oclCommandQueue != null)
            {
                oclCommandQueue.Dispose();
                oclCommandQueue = null;
            }

            if (oclKernel != null)
            {
                oclKernel.Dispose();
                oclKernel = null;
            }

            ComputeProgram oclProgram = null;

            try
            {
                oclContext = new ComputeContext(new ComputeDevice[] { oclDevices[deviceIndx] },
                                                new ComputeContextPropertyList(oclDevices[deviceIndx].Platform), null, IntPtr.Zero);

                oclCommandQueue = new ComputeCommandQueue(oclContext, oclDevices[deviceIndx],
                                                          ComputeCommandQueueFlags.None);

                oclProgram = new ComputeProgram(oclContext,
                                                Encoding.Default.GetString(Properties.Resources.Test));

                oclProgram.Build(new ComputeDevice[] { oclDevices[deviceIndx] }, "", null, IntPtr.Zero);

                oclKernel = oclProgram.CreateKernel("Test");
            }
            catch (BuildProgramFailureComputeException ex)
            {
                string buildLog = oclProgram.GetBuildLog(oclDevices[deviceIndx]);
                throw new Exception(buildLog, ex);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (oclProgram != null)
                {
                    oclProgram.Dispose();
                    oclProgram = null;
                }
            }
        }
        private void BuildEthashProgram()
        {
            ComputeDevice computeDevice = OpenCLDevice.GetComputeDevice();

            try { mProgramArrayMutex.WaitOne(5000); } catch (Exception) { }

            if (mEthashProgramArray.ContainsKey(new long[] { DeviceIndex, mEthashLocalWorkSizeArray[0] }))
            {
                mEthashProgram      = mEthashProgramArray[new long[] { DeviceIndex, mEthashLocalWorkSizeArray[0] }];
                mEthashDAGKernel    = mEthashDAGKernelArray[new long[] { DeviceIndex, mEthashLocalWorkSizeArray[0] }];
                mEthashSearchKernel = mEthashSearchKernelArray[new long[] { DeviceIndex, mEthashLocalWorkSizeArray[0] }];
            }
            else
            {
                try
                {
                    if (mEthashLocalWorkSizeArray[0] != 192)
                    {
                        throw new Exception("No suitable binary file was found.");
                    }
                    string fileName = @"BinaryKernels\" + computeDevice.Name + "_ethash.bin";
                    byte[] binary   = System.IO.File.ReadAllBytes(fileName);
                    mEthashProgram = new ComputeProgram(Context, new List <byte[]>()
                    {
                        binary
                    }, new List <ComputeDevice>()
                    {
                        computeDevice
                    });
                    MainForm.Logger("Loaded " + fileName + " for Device #" + DeviceIndex + ".");
                }
                catch (Exception)
                {
                    //MainForm.Logger("ex.message: " + ex.Message);
                    String source = System.IO.File.ReadAllText(@"Kernels\ethash.cl");
                    mEthashProgram = new ComputeProgram(Context, source);
                    MainForm.Logger(@"Loaded Kernels\ethash.cl for Device #" + DeviceIndex + ".");
                }
                String buildOptions = (OpenCLDevice.GetVendor() == "AMD"    ? "-O1 " :
                                       OpenCLDevice.GetVendor() == "NVIDIA" ? "" : // "-cl-nv-opt-level=1 -cl-nv-maxrregcount=256 " :
                                       "")
                                      + " -IKernels -DWORKSIZE=" + mEthashLocalWorkSizeArray[0];
                try
                {
                    mEthashProgram.Build(OpenCLDevice.DeviceList, buildOptions, null, IntPtr.Zero);
                }
                catch (Exception)
                {
                    MainForm.Logger(mEthashProgram.GetBuildLog(computeDevice));
                    throw;
                }
                MainForm.Logger("Built Ethash program for Device #" + DeviceIndex + ".");
                MainForm.Logger("Build options: " + buildOptions);
                mEthashProgramArray[new long[] { DeviceIndex, mEthashLocalWorkSizeArray[0] }]      = mEthashProgram;
                mEthashDAGKernelArray[new long[] { DeviceIndex, mEthashLocalWorkSizeArray[0] }]    = mEthashDAGKernel = mEthashProgram.CreateKernel("GenerateDAG");
                mEthashSearchKernelArray[new long[] { DeviceIndex, mEthashLocalWorkSizeArray[0] }] = mEthashSearchKernel = mEthashProgram.CreateKernel("search");
            }

            try { mProgramArrayMutex.ReleaseMutex(); } catch (Exception) { }
        }
        public void BuildNeoScryptProgram()
        {
            ComputeDevice computeDevice = OpenCLDevice.GetComputeDevice();

            try { mProgramArrayMutex.WaitOne(5000); } catch (Exception) { }

            if (mNeoScryptProgramArray.ContainsKey(new ProgramArrayIndex(DeviceIndex, mNeoScryptLocalWorkSizeArray[0])))
            {
                mNeoScryptProgram      = mNeoScryptProgramArray[new ProgramArrayIndex(DeviceIndex, mNeoScryptLocalWorkSizeArray[0])];
                mNeoScryptSearchKernel = mNeoScryptSearchKernelArray[new ProgramArrayIndex(DeviceIndex, mNeoScryptLocalWorkSizeArray[0])];
            }
            else
            {
                String source = System.IO.File.ReadAllText(@"Kernels\neoscrypt.cl");
                mNeoScryptProgram = new ComputeProgram(Context, source);
                MainForm.Logger(@"Loaded Kernels\neoscrypt.cl for Device #" + DeviceIndex + ".");
                String buildOptions = (OpenCLDevice.GetVendor() == "AMD" ? "-O5 -legacy" : // "-legacy" :
                                       OpenCLDevice.GetVendor() == "NVIDIA" ? "" :         //"-cl-nv-opt-level=1 -cl-nv-maxrregcount=256 " :
                                       "")
                                      + " -IKernels -DWORKSIZE=" + mNeoScryptLocalWorkSizeArray[0];
                try {
                    mNeoScryptProgram.Build(OpenCLDevice.DeviceList, buildOptions, null, IntPtr.Zero);
                } catch (Exception) {
                    MainForm.Logger(mNeoScryptProgram.GetBuildLog(computeDevice));
                    throw;
                }
                MainForm.Logger("Built NeoScrypt program for Device #" + DeviceIndex + ".");
                MainForm.Logger("Build options: " + buildOptions);
                mNeoScryptProgramArray[new ProgramArrayIndex(DeviceIndex, mNeoScryptLocalWorkSizeArray[0])]      = mNeoScryptProgram;
                mNeoScryptSearchKernelArray[new ProgramArrayIndex(DeviceIndex, mNeoScryptLocalWorkSizeArray[0])] = mNeoScryptSearchKernel = mNeoScryptProgram.CreateKernel("search");
            }

            try { mProgramArrayMutex.ReleaseMutex(); } catch (Exception) { }
        }
Exemplo n.º 11
0
        public static ComputeProgram CreateProgram(string source)
        {
            //string realType = Real.Size == sizeof(double) ? "double" : "float";
            string realType = "float";

            //For setting precision of floating point
            source = REAL_HEADER_STRING + source;

            //Add at double precision
            if (realType == "double")
            {
                source = USE_DOUBLE_HEADER_STRING + source;
            }

            ComputeProgram program = new ComputeProgram(Context, source);

            try
            {
                program.Build(Devices, $"-D REAL={realType} -Werror", null, IntPtr.Zero);
            }
            catch
            {
                MessageBox.Show(program.GetBuildLog(Devices[DeviceIndex]));
            }

            return(program);
        }
Exemplo n.º 12
0
        public string vectorSum()
        {
            string vecSum = @"
                __kernel void vectorSum(__global float *v1, __global float *v2, __global float *v3) {
                    int i = get_global_id(0);
                    v3[i] = v1[i] + v2[i];
                }
            ";
            int    size   = 100000;

            float[] v1_ = new float[size];
            float[] v2_ = new float[size];
            float[] v3_ = new float[size];
            for (var i = 0; i < size; i++)
            {
                v1_[i] = (float)i;
                v2_[i] = (float).5f;
            }
            var platform_ = ComputePlatform.Platforms[0];
            ComputeContextPropertyList properties = new ComputeContextPropertyList(platform_);
            ComputeContext             ctx        = new ComputeContext(ComputeDeviceTypes.Gpu, properties, null, IntPtr.Zero);
            ComputeCommandQueue        commands   = new ComputeCommandQueue(ctx, ctx.Devices[0], ComputeCommandQueueFlags.None);
            ComputeProgram             program    = new ComputeProgram(ctx, vecSum);

            try
            {
                program.Build(null, null, null, IntPtr.Zero);
                Console.WriteLine("program build completed");
            }
            catch
            {
                string log = program.GetBuildLog(ctx.Devices[0]);
            }
            ComputeBuffer <float> v1, v2, v3;

            v1 = new ComputeBuffer <float>(ctx, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, v1_);
            v2 = new ComputeBuffer <float>(ctx, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, v2_);
            v3 = new ComputeBuffer <float>(ctx, ComputeMemoryFlags.WriteOnly | ComputeMemoryFlags.CopyHostPointer, v3_);
            long[] worker = { size };
            commands.WriteToBuffer(v1_, v1, false, null);
            commands.WriteToBuffer(v2_, v2, false, null);
            ComputeKernel sumKernal = program.CreateKernel("vectorSum");

            Console.WriteLine("kernal created");
            sumKernal.SetMemoryArgument(0, v1);
            sumKernal.SetMemoryArgument(1, v2);
            sumKernal.SetMemoryArgument(2, v3);
            commands.Execute(sumKernal, null, worker, null, null);
            Console.WriteLine("Executed");
            commands.ReadFromBuffer <float>(v3, ref v3_, false, null);
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < size; i++)
            {
                sb.AppendFormat("{0} + {1} = {2}<br>", v1_[i].ToString(), v2_[i].ToString(), v3_[i].ToString());
            }
            var sum_expression_result = sb.ToString();

            return(sum_expression_result);
        }
Exemplo n.º 13
0
        public OpenCLProgram(string sourceFile)
        {
            // pick first platform
            SelectBestDevice();
            // load opencl source
            string clSource = "";

            try
            {
                var streamReader = new StreamReader(sourceFile);
                clSource = streamReader.ReadToEnd();
                streamReader.Close();
            }
            catch
            {
                FatalError("File not found:\n" + sourceFile);
            }
            // create program with opencl source
            program = new ComputeProgram(context, clSource);
            // compile opencl source
            try
            {
                program.Build(null, null, null, IntPtr.Zero);
            }
            catch
            {
                FatalError("Error in kernel code:\n" + program.GetBuildLog(context.Devices[0]));
            }
            // create a command queue with first gpu found
            queue = new ComputeCommandQueue(context, context.Devices[0], 0);
        }
Exemplo n.º 14
0
	// initialiseer OpenCL
	static void InitCL()
	{
		// kies platform 0 (op sommige machines moet dit 1 of 2 zijn)
		var platform = ComputePlatform.Platforms[CLPlatform];
		Console.Write( "initializing OpenCL... " + platform.Name + " (" + platform.Profile + ").\n" );
		Console.Write( platform.Devices.First().Name + " (" + platform.Devices.First().Type + ")\n");
		Console.Write( (platform.Devices.First().GlobalMemorySize / 1024 / 1024) );
		Console.WriteLine( " MiB global memory / " + (platform.Devices.First().LocalMemorySize / 1024) + " KiB local memory");
		// maak een compute context
		context = new ComputeContext( ComputeDeviceTypes.Gpu, new ComputeContextPropertyList( platform ), null, IntPtr.Zero );
		// laad opencl programma
		var streamReader = new StreamReader( "../../program.cl" );
		string clSource = streamReader.ReadToEnd();
		streamReader.Close();
		// compileer opencl source code
		program = new ComputeProgram( context, clSource );
		try
		{
			program.Build( null, null, null, IntPtr.Zero );
		}
		catch
		{
			// fout in OpenCL code; check console window voor details.
			Console.Write( "error in kernel code:\n" );
			Console.Write( program.GetBuildLog( context.Devices[0] ) + "\n" );
		}
		// maak een commandorij
		queue = new ComputeCommandQueue( context, context.Devices[0], 0 );
		// lokaliseer de gewenste kernel in het programma
		kernel = program.CreateKernel( "device_function" );
		// alloceer data in RAM
		
	}
Exemplo n.º 15
0
        public BlockedMatMulThread(ComputePlatform platform, ComputeDevice device, int inN, float[] inA, float[] inB)
        {
            ComputeDevice[] devices = { device };
            context = new ComputeContext(devices, new ComputeContextPropertyList(platform), null, IntPtr.Zero);
            program = new ComputeProgram(context, clProgramSource);

            try
            {
                program.Build(null, null, null, IntPtr.Zero);
            }
            catch (BuildProgramFailureComputeException e)
            {
                string buildLog = program.GetBuildLog(device);
                Console.WriteLine(buildLog);
                throw;
            }
            kernel = program.CreateKernel("mmul");
            queue  = new ComputeCommandQueue(context, device, ComputeCommandQueueFlags.None);

            n = inN;
            a = new ComputeBuffer <float>(context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, inA);
            b = new ComputeBuffer <float>(context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, inB);
            int resultCount = (int)(device.MaxMemoryAllocationSize / n / n / sizeof(float));

            results = new ComputeBuffer <float> [resultCount];
            for (int i = 0; i < results.Length; ++i)
            {
                results[i] = new ComputeBuffer <float>(context, ComputeMemoryFlags.WriteOnly, n * n);
            }

            HaltRequested     = false;
            operationCounter  = 0;
            completionCounter = 0;
            startTime         = 0;
        }
Exemplo n.º 16
0
        public GPURadixSort(
            ComputeCommandQueue commandQue,
            ComputeContext context,
            ComputeDevice device
            )
        {
            gpuConstants   = new GPUConstants();
            gpuConstants.L = radix_BitsL;
            gpuConstants.numGroupsPerBlock = NumGroupsPerBlock;
            gpuConstants.R = R;
            gpuConstants.numThreadsPerGroup = numThreadsPerBlock / NumGroupsPerBlock;
            gpuConstants.numThreadsPerBlock = numThreadsPerBlock;
            gpuConstants.numBlocks          = numBlocks;
            gpuConstants.numRadices         = num_Radices;
            gpuConstants.numRadicesPerBlock = num_Radices / numBlocks;
            gpuConstants.bitMask            = BIT_MASK_START;
            counters.Initialize();
            ComputeErrorCode error;

            cxGPUContext   = context.Handle;
            cqCommandQueue = commandQue.Handle;
            _device        = device.Handle;
            //Create a command queue, where all of the commands for execution will be added

            /*cqCommandQueue = CL10.CreateCommandQueue(cxGPUContext, _device, (CommandQueueProperties)0, out  error);
             * CheckErr(error, "CL10.CreateCommandQueue");*/
            string programSource = System.IO.File.ReadAllText(programPath);

            IntPtr[] progSize = new IntPtr[] { (IntPtr)programSource.Length };
            string   flags    = "-cl-fast-relaxed-math";

            ComputeProgram prog = new ComputeProgram(context, programSource);

            prog.Build(new List <ComputeDevice>()
            {
                device
            }, flags, null, IntPtr.Zero);


            if (prog.GetBuildStatus(device) != ComputeProgramBuildStatus.Success)
            {
                Debug.WriteLine(prog.GetBuildLog(device));
                throw new ArgumentException("UNABLE to build programm");
            }
            //            ComputeProgram clProgramRadix = CL10.CreateProgramWithSource(cxGPUContext, 1, new[] { programSource },progSize,
            //                out error);

            CLProgramHandle clProgramRadix = prog.Handle;



            ckSetupAndCount = CL10.CreateKernel(clProgramRadix, "SetupAndCount", out error);
            CheckErr(error, "CL10.CreateKernel");
            ckSumIt = CL10.CreateKernel(clProgramRadix, "SumIt", out error);
            CheckErr(error, "CL10.CreateKernel");
            ckReorderingKeysOnly = CL10.CreateKernel(clProgramRadix, "ReorderingKeysOnly", out error);
            CheckErr(error, "CL10.CreateKernel");
            ckReorderingKeyValue = CL10.CreateKernel(clProgramRadix, "ReorderingKeyValue", out error);
            CheckErr(error, "CL10.CreateKernel");
        }
Exemplo n.º 17
0
        void InitComputeKernel()
        {
            if (this.openCLSources == null)
            {
                GetOpenCLSources();
            }

            var properties = new ComputeContextPropertyList(this.computeDevice.Platform);

            this.computeContext = new ComputeContext(new[] { this.computeDevice }, properties, null, IntPtr.Zero);
            this.computeProgram = new ComputeProgram(this.computeContext, this.openCLSources);

            try
            {
                this.computeProgram.Build(new[] { this.computeDevice }, null, null, IntPtr.Zero);
            }

            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(computeProgram.GetBuildLog(this.computeDevice));
            }

            this.computeKernels = this.computeProgram.CreateAllKernels().ToList();
            this.computeKernel  = this.computeKernels.First(k => k.FunctionName == openCLKernelFunction);
        }
Exemplo n.º 18
0
        public void Load(string directory, string kernelFileName, string function)
        {
#if DEBUG
            DeleteCache();
#endif

            m_platform = ComputePlatform.Platforms[0];

            Context = new ComputeContext(ComputeDeviceTypes.Gpu,
                                         new ComputeContextPropertyList(m_platform), null, IntPtr.Zero);

            m_graphicsCard = Context.Devices[0];

            Queue = new ComputeCommandQueue(Context, m_graphicsCard, ComputeCommandQueueFlags.None);

            ComputeProgram program = new ComputeProgram(Context, GetKernelSource(directory + "/" + kernelFileName));
            try
            {
                program.Build(null, "-I " + directory, null, IntPtr.Zero);
            }
            catch
            {
                string error = program.GetBuildLog(m_graphicsCard);
                throw new Exception(error);
            }

            Program = program.CreateKernel(function);
        }
Exemplo n.º 19
0
        public ComputeKernel GetKernel(string file, string kernelName)
        {
            var program = new ComputeProgram(Context, new StreamReader(@"CL\" + file).ReadToEnd());

            try
            {
                program.Build(null, null, null, IntPtr.Zero);
            }
            catch (Exception)
            {
                var buildLog = program.GetBuildLog(Device);
                throw new Exception(buildLog);
            }
            System.Diagnostics.Debug.WriteLine(program.GetBuildLog(Device));
            return(program.CreateKernel(kernelName));
        }
Exemplo n.º 20
0
        protected ComputeProgram BuildProgram(string programName, long localWorkSize, string optionsAMD, string optionsNVIDIA, string optionsOthers)
        {
            ComputeProgram program;
            string         defultBinaryFilePath = @"BinaryKernels\" + ComputeDevice.Name + "_" + programName + "_" + localWorkSize + ".bin";
            string         savedBinaryFilePath  = (MainForm.SavedOpenCLBinaryKernelPathBase + @"\") + ComputeDevice.Name + "_" + programName + "_" + localWorkSize + ".bin";
            string         sourceFilePath       = @"Kernels\" + programName + ".cl";
            String         buildOptions         = (OpenCLDevice.GetVendor() == "AMD" ? optionsAMD : OpenCLDevice.GetVendor() == "NVIDIA" ? optionsNVIDIA : optionsOthers) + " -IKernels -DWORKSIZE=" + localWorkSize;

            try {
                if (!MainForm.UseDefaultOpenCLBinariesChecked)
                {
                    throw new Exception();
                }
                byte[] binary = System.IO.File.ReadAllBytes(defultBinaryFilePath);
                program = new ComputeProgram(Context, new List <byte[]>()
                {
                    binary
                }, new List <ComputeDevice>()
                {
                    ComputeDevice
                });
                MainForm.Logger("Loaded " + defultBinaryFilePath + " for Device #" + DeviceIndex + ".");
            } catch (Exception) {
                try {
                    if (!MainForm.ReuseCompiledBinariesChecked)
                    {
                        throw new Exception();
                    }
                    byte[] binary = System.IO.File.ReadAllBytes(savedBinaryFilePath);
                    program = new ComputeProgram(Context, new List <byte[]>()
                    {
                        binary
                    }, new List <ComputeDevice>()
                    {
                        ComputeDevice
                    });
                    MainForm.Logger("Loaded " + savedBinaryFilePath + " for Device #" + DeviceIndex + ".");
                } catch (Exception) {
                    String source = System.IO.File.ReadAllText(sourceFilePath);
                    program = new ComputeProgram(Context, source);
                    MainForm.Logger(@"Loaded " + sourceFilePath + " for Device #" + DeviceIndex + ".");
                }
            }
            try {
                program.Build(OpenCLDevice.DeviceList, buildOptions, null, IntPtr.Zero);
                if (MainForm.ReuseCompiledBinariesChecked)
                {
                    System.IO.File.WriteAllBytes(savedBinaryFilePath, program.Binaries[0]);
                }
            } catch (Exception) {
                MainForm.Logger(program.GetBuildLog(ComputeDevice));
                program.Dispose();
                throw;
            }
            MainForm.Logger("Built " + programName + " program for Device #" + DeviceIndex + ".");
            MainForm.Logger("Build options: " + buildOptions);

            return(program);
        }
Exemplo n.º 21
0
        public void BuildLbryProgram()
        {
            ComputeDevice computeDevice = OpenCLDevice.GetComputeDevice();

            try { mProgramArrayMutex.WaitOne(5000); } catch (Exception) { }

            if (mLbryProgramArray.ContainsKey(new ProgramArrayIndex(DeviceIndex, mLbryLocalWorkSizeArray[0])))
            {
                mLbryProgram      = mLbryProgramArray[new ProgramArrayIndex(DeviceIndex, mLbryLocalWorkSizeArray[0])];
                mLbrySearchKernel = mLbrySearchKernelArray[new ProgramArrayIndex(DeviceIndex, mLbryLocalWorkSizeArray[0])];
            }
            else
            {
                try
                {
                    if (mLbryLocalWorkSizeArray[0] != 256)
                    {
                        throw new Exception("No suitable binary file was found.");
                    }
                    string fileName = @"BinaryKernels\" + computeDevice.Name + "_lbry.bin";
                    byte[] binary   = System.IO.File.ReadAllBytes(fileName);
                    mLbryProgram = new ComputeProgram(Context, new List <byte[]>()
                    {
                        binary
                    }, new List <ComputeDevice>()
                    {
                        computeDevice
                    });
                    //MainForm.Logger("Loaded " + fileName + " for Device #" + DeviceIndex + ".");
                }
                catch (Exception)
                {
                    String source = System.IO.File.ReadAllText(@"Kernels\lbry.cl");
                    mLbryProgram = new ComputeProgram(Context, source);
                    //MainForm.Logger(@"Loaded Kernels\lbry.cl for Device #" + DeviceIndex + ".");
                }
                String buildOptions = (OpenCLDevice.GetVendor() == "AMD" ? "-O1 " : //"-O1 " :
                                       OpenCLDevice.GetVendor() == "NVIDIA" ? "" :  //"-cl-nv-opt-level=1 -cl-nv-maxrregcount=256 " :
                                       "")
                                      + " -IKernels -DWORKSIZE=" + mLbryLocalWorkSizeArray[0] + " -DITERATIONS=" + mIterations;
                try
                {
                    mLbryProgram.Build(OpenCLDevice.DeviceList, buildOptions, null, IntPtr.Zero);
                }
                catch (Exception)
                {
                    MainForm.Logger(mLbryProgram.GetBuildLog(computeDevice));
                    throw;
                }
                //MainForm.Logger("Built Lbry program for Device #" + DeviceIndex + ".");
                //MainForm.Logger("Build options: " + buildOptions);
                mLbryProgramArray[new ProgramArrayIndex(DeviceIndex, mLbryLocalWorkSizeArray[0])]      = mLbryProgram;
                mLbrySearchKernelArray[new ProgramArrayIndex(DeviceIndex, mLbryLocalWorkSizeArray[0])] = mLbrySearchKernel = mLbryProgram.CreateKernel("search_combined");
            }

            try { mProgramArrayMutex.ReleaseMutex(); } catch (Exception) { }
        }
Exemplo n.º 22
0
        private void OnProgramBuilt(ComputeProgram program, ComputeDevice device)
        {
            var status = program.GetBuildStatus(device);

            if (status == ComputeProgramBuildStatus.Error)
            {
                var log = program.GetBuildLog(device);
                Console.WriteLine(log);
            }
        }
Exemplo n.º 23
0
        public int ArrayTest(int[,] a1, int[,] b)
        {
            Point f;

            int[,] a = new int[2, 2];
            MyPoint[] plist = new MyPoint[100000];
            MyPoint   p1    = new MyPoint()
            {
                X = 1, Y = 1
            };
            MyPoint p2 = new MyPoint()
            {
                X = 2, Y = 2
            };

            plist[0] = p1;
            plist[1] = p2;


            IntPtr dataaddr_a = Marshal.UnsafeAddrOfPinnedArrayElement(plist, 0);
            ComputeBuffer <MyPoint> abuffer = new ComputeBuffer <MyPoint>(context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, plist);

            string         source  = Encoding.ASCII.GetString(FZYK.Nest.Properties.Resources.nest);
            ComputeProgram program = new ComputeProgram(context, source);

            try
            {
                program.Build(null, null, null, IntPtr.Zero);
            }
            catch (Exception)
            {
                var log = program.GetBuildLog(context.Devices[0]);
                Debugger.Break();
            }

            ComputeKernel kernel = program.CreateKernel("Sum");

            ComputeBuffer <MyPoint> outdata = new ComputeBuffer <MyPoint>(context, ComputeMemoryFlags.ReadWrite, plist.Length);

            kernel.SetMemoryArgument(0, abuffer);
            kernel.SetMemoryArgument(1, outdata);

            commands.Execute(kernel, null, new long[] { 2 }, null, events);

            MyPoint[] myresult = new MyPoint[2];

            GCHandle arrCHandle = GCHandle.Alloc(myresult, GCHandleType.Pinned);

            commands.Read(outdata, true, 0, 2, arrCHandle.AddrOfPinnedObject(), events);
            MyPoint[] test = myresult;
            arrCHandle.Free();

            return(0);
        }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            int w = 11, h = 11, sx = 5, sy = 5, iters = 2;

            var properties = new ComputeContextPropertyList(ComputePlatform.Platforms[0]);
            var context    = new ComputeContext(ComputeDeviceTypes.All, properties, null, IntPtr.Zero);
            var quene      = new ComputeCommandQueue(context, ComputePlatform.Platforms[0].Devices[0], ComputeCommandQueueFlags.None);

            //Компиляция программы
            var prog = new ComputeProgram(context, Source);

            try
            {
                prog.Build(context.Devices, "", null, IntPtr.Zero);
            }
            catch
            {
                Console.WriteLine(prog.GetBuildLog(context.Devices[0]));
            }
            //Создание ядра
            var kernel = prog.CreateKernel("Test");


            var mat = new float[w * h];

            for (int i = 0; i < w * h; i++)
            {
                mat[i] = (i == w * sy + sx) ? 1f : 0f;
            }

            var mat1 = new ComputeBuffer <float>(context, ComputeMemoryFlags.ReadWrite | ComputeMemoryFlags.UseHostPointer, mat);
            var mat2 = new ComputeBuffer <float>(context, ComputeMemoryFlags.ReadWrite, w * h);

            kernel.SetMemoryArgument(0, mat1);
            kernel.SetMemoryArgument(1, mat2);
            kernel.SetValueArgument(2, iters);
            kernel.SetValueArgument(3, w);
            kernel.SetValueArgument(4, h);

            quene.Execute(kernel, null, new long[] { (long)h, (long)w }, null, null);

            quene.ReadFromBuffer(mat1, ref mat, true, null);

            for (int i = 0; i < h; i++)
            {
                for (int j = 0; j < w; j++)
                {
                    Console.Write($"{mat[i*w+j]:.00} ");
                }
                Console.WriteLine();
            }

            Console.ReadKey();
        }
Exemplo n.º 25
0
 private static ComputeKernel GetKernel(ComputeProgram program)
 {
     try
     {
         return(program.CreateKernel("place"));
     }
     catch
     {
         string log = program.GetBuildLog(program.Context.Platform.Devices[0]);
         Console.WriteLine(log);
         throw;
     }
 }
Exemplo n.º 26
0
        private Tuple <TFP[], TFP[]> Compute(int imageWidth, int imageHeight, int unit, float originx, float originy, string funcCode, string funcdxCode, string funcdyCode)
        {
            int w  = imageWidth - 2;
            int h  = imageHeight - 2;
            int cx = imageWidth / 2;
            int cy = imageHeight / 2;

            int bufferSize = w * h;

            ComputeBuffer <TFP> points = new ComputeBuffer <TFP>(context, ComputeMemoryFlags.WriteOnly, bufferSize);

            string source = Encoding.ASCII.GetString(Properties.Resources.function_vis);

            source = source.Replace("{func}", funcCode);
            source = source.Replace("{dfuncdx}", funcdxCode);
            source = source.Replace("{dfuncdy}", funcdyCode);

            if (fpType == FPType.FP64AMD)
            {
                source = "#define AMDFP64\n" + source;
            }
            else if (fpType == FPType.FP64)
            {
                source = "#define FP64\n" + source;
            }

            ComputeProgram program = new ComputeProgram(context, source);

            try
            {
                program.Build(null, null, null, IntPtr.Zero);
            }
            catch (Exception)
            {
                var log = program.GetBuildLog(context.Devices[0]);
                Debugger.Break();
            }

            ComputeKernel kernelx = program.CreateKernel("ComputeX");
            ComputeKernel kernely = program.CreateKernel("ComputeY");

            TFP[] pointsArrayX = RunKernal(unit, w, h, cx, cy, originx, originy, bufferSize, points, kernelx);
            TFP[] pointsArrayY = RunKernal(unit, w, h, cx, cy, originx, originy, bufferSize, points, kernely);

            kernelx.Dispose();
            kernely.Dispose();
            program.Dispose();
            points.Dispose();

            return(Tuple.Create(pointsArrayX, pointsArrayY));
        }
Exemplo n.º 27
0
        /// <summary>
        /// Called when the window has finished loading.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        /// Initialises the OpenCL parts that can be cached and re-used. Compiles the kernels and sets up the larger data storage
        /// properties.
        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            platformList = ComputePlatform.Platforms;
            context      = new ComputeContext(ComputeDeviceTypes.Gpu, new ComputeContextPropertyList(platformList[0]),
                                              null, IntPtr.Zero);

            var code = File.ReadAllText(@"D:\Users\Tony\Documents\tr-robot-football\Simulator\field_kernel.cl");

            using (var program = new ComputeProgram(context, code))
            {
                try
                {
                    program.Build(context.Devices, null, null, IntPtr.Zero);
                }
                catch (BuildProgramFailureComputeException)
                {
                    var s = program.GetBuildLog(context.Devices[0]);
                    MessageBox.Show(s);
                    Close();
                }

                kernel           = program.CreateKernel("main");
                possessionKernel = program.CreateKernel("possessionMain");
                colourKernel     = program.CreateKernel("colorize");
                gradientKernel   = program.CreateKernel("calculateGradient");
            }

            gridWidth = (int)Math.Ceiling(FieldWidth / GridResolution);
            var remainder = gridWidth % WorkGroupSize;

            gridWidth += WorkGroupSize - remainder;

            gridHeight  = (int)Math.Ceiling(FieldHeight / GridResolution);
            remainder   = gridHeight % WorkGroupSize;
            gridHeight += WorkGroupSize - remainder;

            var length = gridWidth * gridHeight;

            points         = new float[length];
            pixels         = new byte[length * 3];
            gradientPoints = new float[length];

            outCl       = new ComputeBuffer <float>(context, ComputeMemoryFlags.ReadWrite, points.Length);
            outPix      = new ComputeBuffer <byte>(context, ComputeMemoryFlags.WriteOnly, pixels.Length);
            outGradient = new ComputeBuffer <float>(context, ComputeMemoryFlags.ReadWrite, gradientPoints.Length);

            pipeServer = new NamedPipeServerStream("fieldRendererPipe", PipeDirection.InOut, 5,
                                                   PipeTransmissionMode.Message, PipeOptions.Asynchronous);
            pipeServer.BeginWaitForConnection(EnvironmentReceived, null);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Creates the kernels.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="code">The code.</param>
        /// <exception cref="CompileException"></exception>
        private void CreateKernels(string code)
        {
            var program = new ComputeProgram(_context, code);

            try
            {
                program.Build(null, null, null, IntPtr.Zero);
                _compiledKernels.AddRange(program.CreateAllKernels());
            }
            catch (Exception ex)
            {
                string log = program.GetBuildLog(_defaultDevice);
                throw new CompileException(string.Format("Compilation error code: {0} \n Message: {1}", ex.Message, log));
            }
        }
Exemplo n.º 29
0
        public void LoadKernel(string Kernel)
        {
            this.kernel = Kernel;
            program     = new ComputeProgram(context, Kernel);

            try
            {
                program.Build(null, null, null, IntPtr.Zero);   //compile
            }
            catch (BuildProgramFailureComputeException)
            {
                string message = program.GetBuildLog(Accelerator.Device);
                throw new ArgumentException(message);
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Compiles the OpenCL program on a given platform
        /// </summary>
        /// <param name="platform">The platform to run this program on</param>
        public void Compile(ComputePlatform platform)
        {
            if (context != null)
            {
                return;
            }

            // Creating context on platform
            context = new ComputeContext(ComputeDeviceTypes.All, new ComputeContextPropertyList(platform), null, IntPtr.Zero); // CPU Fallback?

            // Reading the static source file
            string include = Resources.noise;

            // Stub
            string stub =
                @"
            __kernel void cl_main(__global Single3 *input, __global int *perm, __global float *output) { 
                int index = get_global_id(0);
                Single3 in_pos = input[index];      
                output[index] = " + module.Code + @";
            }

            __kernel void cl_main_range(ImplicitCube cube, __global int *perm, __global float *output) {
                int index = cube.lengthY * cube.lengthX * get_global_id(2) + cube.lengthX * get_global_id(1) + get_global_id(0);
                Single3 in_pos = { cube.startX + get_global_id(0) * cube.offsetX, cube.startY + get_global_id(1) * cube.offsetY, cube.startZ + get_global_id(2) * cube.offsetZ };
                output[index] = " + module.Code + @";
            }";

            completeSource = include + stub;

            ComputeProgram program = new ComputeProgram(context, completeSource);

            try
            {
                program.Build(context.Platform.Devices, null, null, IntPtr.Zero);
            }
            catch
            {
                // TODO: Replace this nasty exception re-throwing
                throw new Exception(program.GetBuildLog(program.Devices[0]));
            }

            kernelExplicit = program.CreateKernel("cl_main");
            kernelImplicit = program.CreateKernel("cl_main_range");

            setupPermutationBuffer();
            queue = new ComputeCommandQueue(context, context.Devices[0], ComputeCommandQueueFlags.None);
        }