コード例 #1
0
ファイル: context.cpp プロジェクト: yangzhengxing/luxrender
Context::Context(LuxRaysDebugHandler handler, const int openclPlatformIndex,
		const bool verb) {
	debugHandler = handler;
	currentDataSet = NULL;
	started = false;
	verbose = verb;

	// Get the list of devices available on the platform
	NativeThreadDeviceDescription::AddDeviceDescs(deviceDescriptions);

#if !defined(LUXRAYS_DISABLE_OPENCL)
	// Platform info
	VECTOR_CLASS<cl::Platform> platforms;
	cl::Platform::get(&platforms);
	for (size_t i = 0; i < platforms.size(); ++i)
		LR_LOG(this, "OpenCL Platform " << i << ": " << platforms[i].getInfo<CL_PLATFORM_VENDOR>().c_str());

	if (openclPlatformIndex < 0) {
		if (platforms.size() > 0) {
			// Just use all the platforms available
			for (size_t i = 0; i < platforms.size(); ++i)
				OpenCLDeviceDescription::AddDeviceDescs(
					platforms[i], DEVICE_TYPE_OPENCL_ALL,
					deviceDescriptions);
		} else
			LR_LOG(this, "No OpenCL platform available");
	} else {
		if ((platforms.size() == 0) || (openclPlatformIndex >= (int)platforms.size()))
			throw std::runtime_error("Unable to find an appropriate OpenCL platform");
		else {
			OpenCLDeviceDescription::AddDeviceDescs(
				platforms[openclPlatformIndex],
				DEVICE_TYPE_OPENCL_ALL, deviceDescriptions);
		}
	}
#endif

	// Print device info
	for (size_t i = 0; i < deviceDescriptions.size(); ++i) {
		DeviceDescription *desc = deviceDescriptions[i];
		LR_LOG(this, "Device " << i << " name: " <<
			desc->GetName());

		LR_LOG(this, "Device " << i << " type: " <<
			DeviceDescription::GetDeviceType(desc->GetType()));

		LR_LOG(this, "Device " << i << " compute units: " <<
			desc->GetComputeUnits());

		LR_LOG(this, "Device " << i << " preferred float vector width: " <<
			desc->GetNativeVectorWidthFloat());

		LR_LOG(this, "Device " << i << " max allocable memory: " <<
			desc->GetMaxMemory() / (1024 * 1024) << "MBytes");

		LR_LOG(this, "Device " << i << " max allocable memory block size: " <<
			desc->GetMaxMemoryAllocSize() / (1024 * 1024) << "MBytes");
	}
}
コード例 #2
0
ファイル: cxOpenCLPrinter.cpp プロジェクト: c0ns0le/CustusX
void OpenCLPrinter::printContextInfo(cl::Context context)
{
	print("--- ContextInfo ---", "");
	VECTOR_CLASS<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();
	print("Number of devices", devices.size());
	for(int i=0; i<devices.size(); ++i)
		printDeviceInfo(devices[i]);
}
コード例 #3
0
ファイル: ocl.cpp プロジェクト: scollinson/luxrays
cl::Program *oclKernelVolatileCache::Compile(cl::Context &context, cl::Device& device,
		const std::string &kernelsParameters, const std::string &kernelSource,
		bool *cached, cl::STRING_CLASS *error) {
	// Check if the kernel is available in the cache
	std::map<std::string, cl::Program::Binaries>::iterator it = kernelCache.find(kernelsParameters);

	if (it == kernelCache.end()) {
		// It isn't available, compile the source
		cl::Program *program = ForcedCompile(
				context, device, kernelsParameters, kernelSource, error);
		if (!program)
			return NULL;

		// Obtain the binaries of the sources
		VECTOR_CLASS<char *> bins = program->getInfo<CL_PROGRAM_BINARIES>();
		assert (bins.size() == 1);
		VECTOR_CLASS<size_t> sizes = program->getInfo<CL_PROGRAM_BINARY_SIZES>();
		assert (sizes.size() == 1);

		if (sizes[0] > 0) {
			// Add the kernel to the cache
			char *bin = new char[sizes[0]];
			memcpy(bin, bins[0], sizes[0]);
			kernels.push_back(bin);

			kernelCache[kernelsParameters] = cl::Program::Binaries(1, std::make_pair(bin, sizes[0]));
		}

		if (cached)
			*cached = false;

		return program;
	} else {
		// Compile from the binaries
		VECTOR_CLASS<cl::Device> buildDevice;
		buildDevice.push_back(device);
		cl::Program *program = new cl::Program(context, buildDevice, it->second);
		program->build(buildDevice);

		if (cached)
			*cached = true;

		return program;
	}
}
コード例 #4
0
CLDeviceSelection::CLDeviceSelection(const QString selectString, bool allowGPU, bool allowCPU)
{
	VECTOR_CLASS<cl::Platform> platforms;
	CL_DETECT_ERROR(cl::Platform::get(&platforms));
	int selectIndex = 0;
	qDebug().nospace().noquote()<<"Making OpenCL device selection with selectstring='"<< selectString<< "', allowGPU="<<allowGPU<<", allowCPU="<<allowCPU<<"";
	for (size_t i = 0; i < platforms.size(); ++i) {
		qDebug().nospace().noquote()<<"Platform-" << i << ": " << QString::fromLocal8Bit(platforms[i].getInfo<CL_PLATFORM_VENDOR>().c_str());

		// Get the list of devices available on the platform
		VECTOR_CLASS<cl::Device> devices;
		platforms[i].getDevices(CL_DEVICE_TYPE_ALL, &devices);

		for (size_t j = 0; j < devices.size(); ++j) {
			bool selected = false;
			auto type=devices[j].getInfo<CL_DEVICE_TYPE>();
			if ((allowGPU && (type == CL_DEVICE_TYPE_GPU)) || (allowCPU && (type == CL_DEVICE_TYPE_CPU))) {
				if (selectString.length() == 0) {
					selected = true;
				} else {
					if (selectString.length() <= selectIndex) {
						qWarning()<< "OpenCL select devices string (opencl.devices.select) has the wrong length";
						exit(1);
					}

					if (selectString.at(selectIndex) == '1') {
						selected = true;
					}
				}
			}
			if (selected) {
				push_back(devices[j]);
			}

			qDebug().nospace()<< " |-- Device-"<<i <<"."<<j <<": "<< devices[j]<<(selected?" [SEL]":" [---]");
			++selectIndex;

		}
	}

	if (size() == 0) {
		qWarning()<<"This program requires OpenCL enabled hardware. Unable to find any OpenCL GPU devices, so quitting";
		exit(1);
	}
}
コード例 #5
0
ファイル: cxOpenCLPrinter.cpp プロジェクト: c0ns0le/CustusX
void OpenCLPrinter::printPlatformAndDeviceInfo()
{
	VECTOR_CLASS<cl::Platform> platforms;
	cl::Platform::get(&platforms);

	VECTOR_CLASS<cl::Device> devices;
    for(unsigned int i = 0; i < platforms.size(); i++)
    {
    	printPlatformInfo(platforms[i]);

		platforms[i].getDevices(CL_DEVICE_TYPE_ALL, &devices);

		for(unsigned int j = 0; j < devices.size(); j++)
		{
            printDeviceInfo(devices[j]);
		}
    }
    print("Number of platforms", platforms.size());
    print("Number of devices", devices.size());
}
コード例 #6
0
ファイル: ocl.cpp プロジェクト: scollinson/luxrays
cl::Program *oclKernelPersistentCache::Compile(cl::Context &context, cl::Device& device,
		const std::string &kernelsParameters, const std::string &kernelSource,
		bool *cached, cl::STRING_CLASS *error) {
	// Check if the kernel is available in the cache

	cl::Platform platform = device.getInfo<CL_DEVICE_PLATFORM>();
	std::string platformName = platform.getInfo<CL_PLATFORM_VENDOR>();
	std::string deviceName = device.getInfo<CL_DEVICE_NAME>();
	std::string deviceUnits = ToString(device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>());
	std::string kernelName = HashString(kernelsParameters) + "-" + HashString(kernelSource) + ".ocl";
	std::string dirName = "kernel_cache/" + appName + "/" + platformName + "/" + deviceName + "/" + deviceUnits;
	std::string fileName = dirName +"/" +kernelName;
	
	if (!boost::filesystem::exists(fileName)) {
		// It isn't available, compile the source
		cl::Program *program = ForcedCompile(
				context, device, kernelsParameters, kernelSource, error);
		if (!program)
			return NULL;

		// Obtain the binaries of the sources
		VECTOR_CLASS<char *> bins = program->getInfo<CL_PROGRAM_BINARIES>();
		assert (bins.size() == 1);
		VECTOR_CLASS<size_t> sizes = program->getInfo<CL_PROGRAM_BINARY_SIZES >();
		assert (sizes.size() == 1);

		// Create the file only if the binaries include something
		if (sizes[0] > 0) {
			// Add the kernel to the cache
			boost::filesystem::create_directories(dirName);
			BOOST_OFSTREAM file(fileName.c_str(), std::ios_base::out | std::ios_base::binary);
			file.write(bins[0], sizes[0]);

			// Check for errors
			char buf[512];
			if (file.fail()) {
				sprintf(buf, "Unable to write kernel file cache %s", fileName.c_str());
				throw std::runtime_error(buf);
			}

			file.close();
		}

		if (cached)
			*cached = false;

		return program;
	} else {
		const size_t kernelSize = boost::filesystem::file_size(fileName);

		if (kernelSize > 0) {
			char *kernelBin = new char[kernelSize];

			BOOST_IFSTREAM file(fileName.c_str(), std::ios_base::in | std::ios_base::binary);
			file.read(kernelBin, kernelSize);

			// Check for errors
			char buf[512];
			if (file.fail()) {
				sprintf(buf, "Unable to read kernel file cache %s", fileName.c_str());
				throw std::runtime_error(buf);
			}

			file.close();

			// Compile from the binaries
			VECTOR_CLASS<cl::Device> buildDevice;
			buildDevice.push_back(device);
			cl::Program *program = new cl::Program(context, buildDevice,
					cl::Program::Binaries(1, std::make_pair(kernelBin, kernelSize)));
			program->build(buildDevice);

			if (cached)
				*cached = true;

			delete[] kernelBin;

			return program;
		} else {
			// Something wrong in the file, remove the file and retry
			boost::filesystem::remove(fileName);

			return Compile(context, device, kernelsParameters, kernelSource, cached, error);
		}
	}
}
コード例 #7
0
ファイル: clUtility.cpp プロジェクト: shocker-0x15/CLeaR
 void printDeviceInfo(const cl::Device &device, cl_device_info info) {
     if (!initialized) {
         printf("not initialized. call initCLUtility().");
     }
     
     printf("%s: ", clDeviceInfoMetaInfos[info].name);
     
     switch (clDeviceInfoMetaInfos[info].infoType) {
         case CLDeviceInfoType_bool: {
             cl_bool val;
             device.getInfo(info, &val);
             printf(val != 0 ? "YES" : "NO");
             break;
         }
         case CLDeviceInfoType_uint: {
             cl_uint val;
             device.getInfo(info, &val);
             printf("%u", val);
             break;
         }
         case CLDeviceInfoType_ulong: {
             cl_ulong val;
             device.getInfo(info, &val);
             printf("%llu", val);
             break;
         }
         case CLDeviceInfoType_size_t: {
             size_t val;
             device.getInfo(info, &val);
             printf("%lu", val);
             break;
         }
         case CLDeviceInfoType_string: {
             std::string val;
             device.getInfo(info, &val);
             printf("%s", val.c_str());
             break;
         }
         case CLDeviceInfoType_size_t_vec: {
             VECTOR_CLASS<size_t> val;
             device.getInfo(info, &val);
             for (uint32_t i = 0; i < val.size() - 1; ++i) {
                 printf("%lu, ", val[i]);
             }
             printf("%lu", val.back());
             break;
         }
         case CLDeviceInfoType_device_id: {
             cl_device_id val;
             device.getInfo(info, &val);
             printf("%#018llx", (uint64_t)val);
             break;
         }
         case CLDeviceInfoType_platform_id: {
             cl_platform_id val;
             device.getInfo(info, &val);
             printf("%#018llx", (uint64_t)val);
             break;
         }
         case CLDeviceInfoType_device_type: {
             cl_device_type val;
             device.getInfo(info, &val);
             switch (val) {
                 case CL_DEVICE_TYPE_CPU:
                     printf("CPU");
                     break;
                 case CL_DEVICE_TYPE_GPU:
                     printf("GPU");
                     break;
                 case CL_DEVICE_TYPE_ACCELERATOR:
                     printf("Accelerator");
                     break;
                 case CL_DEVICE_TYPE_CUSTOM:
                     printf("Custom");
                     break;
                 default:
                     break;
             }
             break;
         }
         case CLDeviceInfoType_device_fp_config: {
             cl_device_fp_config val;
             device.getInfo(info, &val);
             if ((val & CL_FP_DENORM) != 0)
                 printf("CL_FP_DENORM ");
             if ((val & CL_FP_INF_NAN) != 0)
                 printf("CL_FP_INF_NAN ");
             if ((val & CL_FP_ROUND_TO_NEAREST) != 0)
                 printf("CL_FP_ROUND_TO_NEAREST ");
             if ((val & CL_FP_ROUND_TO_ZERO) != 0)
                 printf("CL_FP_ROUND_TO_ZERO ");
             if ((val & CL_FP_ROUND_TO_INF) != 0)
                 printf("CL_FP_ROUND_TO_INF ");
             if ((val & CL_FP_FMA) != 0)
                 printf("CL_FP_FMA ");
             if ((val & CL_FP_SOFT_FLOAT) != 0)
                 printf("CL_FP_SOFT_FLOAT ");
             if ((val & CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT) != 0)
                 printf("CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT ");
             break;
         }
         case CLDeviceInfoType_device_local_mem_type: {
             cl_device_local_mem_type val;
             device.getInfo(info, &val);
             switch (val) {
                 case CL_LOCAL:
                     printf("Local");
                     break;
                 case CL_GLOBAL:
                     printf("Global");
                 default:
                     break;
             }
             break;
         }
         case CLDeviceInfoType_device_mem_cache_type: {
             cl_device_mem_cache_type val;
             device.getInfo(info, &val);
             switch (val) {
                 case CL_NONE:
                     printf("None");
                     break;
                 case CL_READ_ONLY_CACHE:
                     printf("Read Only Cache");
                     break;
                 case CL_READ_WRITE_CACHE:
                     printf("Read Write Cache");
                     break;
                 default:
                     break;
             }
             break;
         }
         case CLDeviceInfoType_device_exec_capabilities: {
             cl_device_exec_capabilities val;
             device.getInfo(info, &val);
             if ((val & CL_EXEC_KERNEL) != 0)
                 printf("CL_EXEC_KERNEL ");
             if ((val & CL_EXEC_NATIVE_KERNEL) != 0)
                 printf("CL_EXEC_NATIVE_KERNEL ");
             break;
         }
         case CLDeviceInfoType_command_queue_properties: {
             cl_command_queue_properties val;
             device.getInfo(info, &val);
             if ((val & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE) != 0)
                 printf("CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE ");
             if ((val & CL_QUEUE_PROFILING_ENABLE) != 0)
                 printf("CL_QUEUE_PROFILING_ENABLE ");
             break;
         }
         case CLDeviceInfoType_device_affinity_domain: {
             cl_device_affinity_domain val;
             device.getInfo(info, &val);
             if ((val & CL_DEVICE_AFFINITY_DOMAIN_NUMA) != 0)
                 printf("CL_DEVICE_AFFINITY_DOMAIN_NUMA ");
             if ((val & CL_DEVICE_AFFINITY_DOMAIN_L4_CACHE) != 0)
                 printf("CL_DEVICE_AFFINITY_DOMAIN_L4_CACHE ");
             if ((val & CL_DEVICE_AFFINITY_DOMAIN_L3_CACHE) != 0)
                 printf("CL_DEVICE_AFFINITY_DOMAIN_L3_CACHE ");
             if ((val & CL_DEVICE_AFFINITY_DOMAIN_L2_CACHE) != 0)
                 printf("CL_DEVICE_AFFINITY_DOMAIN_L2_CACHE ");
             if ((val & CL_DEVICE_AFFINITY_DOMAIN_L1_CACHE) != 0)
                 printf("CL_DEVICE_AFFINITY_DOMAIN_L1_CACHE ");
             if ((val & CL_DEVICE_AFFINITY_DOMAIN_NEXT_PARTITIONABLE) != 0)
                 printf("CL_DEVICE_AFFINITY_DOMAIN_NEXT_PARTITIONABLE ");
             break;
         }
         case CLDeviceInfoType_device_partition_property_vec: {
             VECTOR_CLASS<cl_device_partition_property> val;
             device.getInfo(info, &val);
             for (uint32_t i = 0; i < val.size(); ++i) {
                 switch (val[i]) {
                     case CL_DEVICE_PARTITION_EQUALLY:
                         printf("CL_DEVICE_PARTITION_EQUALLY");
                         break;
                     case CL_DEVICE_PARTITION_BY_COUNTS:
                         printf("CL_DEVICE_PARTITION_BY_COUNTS");
                         break;
                     case CL_DEVICE_PARTITION_BY_COUNTS_LIST_END:
                         printf("CL_DEVICE_PARTITION_BY_COUNTS_LIST_END");
                         break;
                     case CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN:
                         printf("CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN");
                         break;
                     default:
                         break;
                 }
                 if (i < val.size() - 1)
                     printf(", ");
             }
             break;
         }
         default:
             break;
     }
     printf("\n");
 }
コード例 #8
0
ファイル: ocl_info.cpp プロジェクト: davidrios/mandel-exps
int main(int argc, char* argv[]) {
	cl_int retCode;

	// get platforms
	const cl_platform_info PLATFORM_INFOS[] = {
		CL_PLATFORM_NAME,
		CL_PLATFORM_VENDOR,
		CL_PLATFORM_PROFILE,
		CL_PLATFORM_VERSION
	};
	VECTOR_CLASS<Platform> platforms;

	retCode = Platform::get(&platforms);
	if (retCode != CL_SUCCESS)
		die("failed to get platforms");

	std::cout << "platforms found: " << platforms.size() << std::endl;
	for (uint i = 0; i < platforms.size(); i++) {
		std::cout << "platform " << i+1 << ": ";
		for (uint j = 0; j < (sizeof(PLATFORM_INFOS) / sizeof(cl_platform_info)); j++) {
			STRING_CLASS info;
			retCode = platforms[i].getInfo(PLATFORM_INFOS[j], &info);
			if (retCode != CL_SUCCESS)
				die("failed to get platform info");
			std::cout << info << " ";
		}
		std::cout << std::endl;

		// get devices
		const cl_device_info DEVICE_INFOS[] = {
			CL_DEVICE_NAME,
			CL_DEVICE_VENDOR,
			CL_DEVICE_PROFILE,
			CL_DEVICE_VERSION,
			CL_DRIVER_VERSION,
			CL_DEVICE_OPENCL_C_VERSION
		};
		VECTOR_CLASS<Device> devices;

		retCode = platforms[i].getDevices(CL_DEVICE_TYPE_ALL, &devices);
		if (retCode != CL_SUCCESS)
			die("  failed to get devices");

		std::cout << "  devices found: " << devices.size() << std::endl;
		for (uint j = 0; j < devices.size(); j++) {
			std::cout << "  device " << j+1 << ": ";
			for (uint k = 0; k < (sizeof(DEVICE_INFOS) / sizeof(cl_device_info)); k++) {
				STRING_CLASS info;
				retCode = devices[j].getInfo(DEVICE_INFOS[k], &info);
				if (retCode != CL_SUCCESS)
					die("  failed to get device info");
				std::cout << info << " ";
			}

			cl_ulong memSize;
			retCode = devices[j].getInfo(CL_DEVICE_GLOBAL_MEM_SIZE, &memSize);
			if (retCode != CL_SUCCESS)
				die("  failed to get device info");
			std::cout << "GlobalMemSize:" << memSize / 1024 / 1024 << "MB ";

			retCode = devices[j].getInfo(CL_DEVICE_LOCAL_MEM_SIZE, &memSize);
			if (retCode != CL_SUCCESS)
				die("  failed to get device info");
			std::cout << "LocalMemSize:" << memSize / 1024 << "KB ";

			std::cout << std::endl;
		}
	}
}
コード例 #9
0
ファイル: oclrenderer.cpp プロジェクト: WarterKu/sfera
OCLRenderer::OCLRenderer(GameLevel *level) : LevelRenderer(level) {
	compiledScene = new CompiledScene(level);

	timeSinceLastCameraEdit = WallClockTime();
	timeSinceLastNoCameraEdit = timeSinceLastCameraEdit;

	//--------------------------------------------------------------------------
	// OpenCL setup
	//--------------------------------------------------------------------------

	vector<cl::Device> selectedDevices;

	// Scan all platforms and devices available
	VECTOR_CLASS<cl::Platform> platforms;
	cl::Platform::get(&platforms);
	const string &selectString = gameLevel->gameConfig->GetOpenCLDeviceSelect();
	size_t selectIndex = 0;
	for (size_t i = 0; i < platforms.size(); ++i) {
		SFERA_LOG("[OCLRenderer] OpenCL Platform " << i << ": " << platforms[i].getInfo<CL_PLATFORM_VENDOR>());

		// Get the list of devices available on the platform
		VECTOR_CLASS<cl::Device> devices;
		platforms[i].getDevices(CL_DEVICE_TYPE_ALL, &devices);

		for (size_t j = 0; j < devices.size(); ++j) {
			SFERA_LOG("[OCLRenderer]   OpenCL device " << j << ": " << devices[j].getInfo<CL_DEVICE_NAME>());
			SFERA_LOG("[OCLRenderer]     Type: " << OCLDeviceTypeString(devices[j].getInfo<CL_DEVICE_TYPE>()));
			SFERA_LOG("[OCLRenderer]     Units: " << devices[j].getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>());
			SFERA_LOG("[OCLRenderer]     Global memory: " << devices[j].getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>() / 1024 << "Kbytes");
			SFERA_LOG("[OCLRenderer]     Local memory: " << devices[j].getInfo<CL_DEVICE_LOCAL_MEM_SIZE>() / 1024 << "Kbytes");
			SFERA_LOG("[OCLRenderer]     Local memory type: " << OCLLocalMemoryTypeString(devices[j].getInfo<CL_DEVICE_LOCAL_MEM_TYPE>()));
			SFERA_LOG("[OCLRenderer]     Constant memory: " << devices[j].getInfo<CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE>() / 1024 << "Kbytes");

			bool selected = false;
			if (!gameLevel->gameConfig->GetOpenCLUseOnlyGPUs() || (devices[j].getInfo<CL_DEVICE_TYPE>() == CL_DEVICE_TYPE_GPU)) {
				if (selectString.length() == 0)
					selected = true;
				else {
					if (selectString.length() <= selectIndex)
						throw runtime_error("OpenCL select devices string (opencl.devices.select) has the wrong length");

					if (selectString.at(selectIndex) == '1')
						selected = true;
				}
			}

			if (selected) {
				selectedDevices.push_back(devices[j]);
				SFERA_LOG("[OCLRenderer]     SELECTED");
			} else
				SFERA_LOG("[OCLRenderer]     NOT SELECTED");

			++selectIndex;
		}
	}

	if (selectedDevices.size() == 0)
		throw runtime_error("Unable to find a OpenCL GPU device");

	// Create synchronization barrier
	barrier = new boost::barrier(selectedDevices.size() + 1);

	totSamplePerPass = 0;
	for (size_t i = 0; i < selectedDevices.size(); ++i)
		totSamplePerPass += gameLevel->gameConfig->GetOpenCLDeviceSamplePerPass(i);

	renderThread.resize(selectedDevices.size(), NULL);
	for (size_t i = 0; i < selectedDevices.size(); ++i) {
		OCLRendererThread *rt = new OCLRendererThread(i, this, selectedDevices[i]);
		renderThread[i] = rt;
	}

	for (size_t i = 0; i < renderThread.size(); ++i)
		renderThread[i]->Start();
}
コード例 #10
0
ファイル: oclutil.cpp プロジェクト: gabrieljt/ocl_util
OCLutil::OCLutil(cl_device_type type,std::string arq,std::string buildOptions,std::string nomeRot,int n)
{

    VECTOR_CLASS<cl::Platform> platforms;
    cl::Platform::get(&platforms);

    if(platforms.size() == 0){
        std::cout<<"No OpenCL platforms were found"<<std::endl;
    }

    int platformID = -1;

    for(unsigned int i = 0; i < platforms.size(); i++) {
        try {
            VECTOR_CLASS<cl::Device> devices;
            platforms[i].getDevices(type, &devices);
            platformID = i;
            break;
        } catch(std::exception e) {
            std::cout<<"Error ao ler plataforma: "<<std::endl;
            continue;
        }
    }


    if(platformID == -1){
        std::cout<<"No compatible OpenCL platform found"<<std::endl;
    }

    cl::Platform platform = platforms[platformID];
    std::cout << "Using platform vendor: " << platform.getInfo<CL_PLATFORM_VENDOR>() << std::endl;


    // Use the preferred platform and create a context
    cl_context_properties cps[] = {
        CL_CONTEXT_PLATFORM,
        (cl_context_properties)(platform)(),
        0
    };

    try {
        context = cl::Context(type, cps);
    } catch(std::exception e) {
        std::cout<<"Failed to create an OpenCL context!"<<std::endl;
    }

    std::string filename = arq;
    std::ifstream sourceFile(filename.c_str());
    if(sourceFile.fail())
        std::cout<<"Failed to open OpenCL source file"<<std::endl;

    std::string sourceCode(
                std::istreambuf_iterator<char>(sourceFile),
                (std::istreambuf_iterator<char>()));
    cl::Program::Sources source(1, std::make_pair(sourceCode.c_str(), sourceCode.length()+1));

    // Make program of the source code in the context
    cl::Program program = cl::Program(context, source);

    VECTOR_CLASS<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();
    std::string deviceInfo;
    cl_ulong memInfo;
    size_t tam;
    cl_uint clUnit;
    int indexDev = 0;
    int maxU = 0;
    for (int i = 0; i < devices.size(); ++i)
    {
        devices[i].getInfo((cl_device_info) CL_DEVICE_NAME, &deviceInfo);
        std::cout << "Device info: " << deviceInfo << std::endl;
        devices[i].getInfo((cl_device_info) CL_DEVICE_VERSION, &deviceInfo);
        std::cout << "Versão CL: " << deviceInfo << std::endl;
        devices[i].getInfo((cl_device_info) CL_DRIVER_VERSION, &deviceInfo);
        std::cout << "Versão Driver: " << deviceInfo << std::endl;
        devices[i].getInfo((cl_device_info) CL_DEVICE_GLOBAL_MEM_SIZE, &memInfo);
        std::cout << "Memoria Global: " << memInfo << std::endl;
        devices[i].getInfo((cl_device_info) CL_DEVICE_LOCAL_MEM_SIZE, &memInfo);
        std::cout << "Memoria Local: " << memInfo << std::endl;
        devices[i].getInfo((cl_device_info) CL_DEVICE_LOCAL_MEM_SIZE, &tam);
        std::cout << "Max tamanho Work-group: " << tam << std::endl;
        devices[i].getInfo((cl_device_info) CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, &clUnit);
        std::cout << "Max dimensao: " << clUnit << std::endl;
        devices[i].getInfo((cl_device_info) CL_DEVICE_MAX_COMPUTE_UNITS, &clUnit);
        std::cout << "Unidades CL: " << clUnit << std::endl;
        std::cout << "*********************************" << std::endl;

        if((int)clUnit>maxU){
            indexDev = i;
            maxU = (int)clUnit;
        }
    }

    // Build program for these specific devices
    cl_int error = program.build(devices, buildOptions.c_str());
    if(error != 0) {
        std::cout << "Build log:" << std::endl << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]) << std::endl;
    }

    std::cout << "Index Dispositino selecionado: " << indexDev << std::endl;
    queue = cl::CommandQueue(context, devices[indexDev]);

    int posi = 0;
    int posf = 0;
    for(int i = 0; i < n; i++){

        posf = nomeRot.find(",",posi);
        std::string nomeRoti;
        if(posf != -1){
            nomeRoti = nomeRot.substr(posi,posf-posi);
        }else{
            nomeRoti = nomeRot.substr(posi);
        }
        std::cout<<"Nome rotina["<<i<<"]: "<<nomeRoti.data()<<std::endl;
        rotina.push_back(cl::Kernel(program, nomeRoti.data()));
        posi = posf + 1;
    }
}