diff --git a/developHw.pro.user b/developHw.pro.user index e00b9b1..379658b 100644 --- a/developHw.pro.user +++ b/developHw.pro.user @@ -1,6 +1,6 @@ - + EnvironmentId diff --git a/include/config/Configuration.h b/include/config/Configuration.h new file mode 100644 index 0000000..132c723 --- /dev/null +++ b/include/config/Configuration.h @@ -0,0 +1,50 @@ +#ifndef CONFIGURATION_H +#define CONFIGURATION_H + +#include +#include + +//#define USE_DBL + +//timeout for which event coordinator waits for events responders +#define EVENT_COORD_TIMEOUT 5000 + +#define US_HOME_PATH "US_HOME" + +#define SCENARIO_EXT ".scn" + +//config file path +#if defined(_WIN32) + + #define CONFIGURATION_PATH QString("D:\\config\\") +#elif defined(__linux__) + #define CONFIGURATION_PATH QString("/home/hasis/Desktop/config/") +#else + #define CONFIGURATION_PATH QString("D:\\config\\") +#endif + +//module names +#define VIEWMODEL_NAME QString("MainViewModel") +#define HARDWARE_NAME QString("Hardware") +#define SCEN_GEN_NAME QString("ScenarioGenerator") +#define LOGGER_NAME QString("Logger") +#define CONF_MAN_NAME QString("ConfigurationManager") +#define CSM_NAME QString("Csm") +#define SSM_NAME QString("Ssm") +#define BIP_NAME QString("Bip") +#define CINE_NAME QString("Evocator") +#define PLAYER_NAME QString("Player") +#define DB_MAN_NAME QString("DatabaseManager") +#define BIP_TESTER_NAME QString("BipTester") +#define HID_NAME QString("Hid") +#define EVOCATOR_NAME QString("Evocator") +#define B_SET_VM_NAME QString("BModeSettingViewModel") +#define B_DISP_VM_NAME QString("BModeDisplayViewModel") +#define IMAGE_VM_NAME QString("ImageViewModel") +#define USER_VM_NAME QString("UserViewModel") +#define PROBE_VM_NAME QString("ProbeViewModel") +#define SIM_VM_NAME QString("SimulationViewModel") +#define TGC_VM_NAME QString("TgcViewModel") +#define USER_NAME QString("sonographer") + +#endif //CONFIGURATION_H diff --git a/include/lib/CL/OpenCL.lib b/include/lib/CL/OpenCL.lib new file mode 100644 index 0000000..7a761ed Binary files /dev/null and b/include/lib/CL/OpenCL.lib differ diff --git a/include/lib/CL/cl.h b/include/lib/CL/cl.h new file mode 100644 index 0000000..4026cbb --- /dev/null +++ b/include/lib/CL/cl.h @@ -0,0 +1,1235 @@ +/******************************************************************************* + * Copyright (c) 2008 - 2012 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + ******************************************************************************/ + +#ifndef __OPENCL_CL_H +#define __OPENCL_CL_H + +#ifdef __APPLE__ +#include +#else +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************************************/ + +typedef struct _cl_platform_id * cl_platform_id; +typedef struct _cl_device_id * cl_device_id; +typedef struct _cl_context * cl_context; +typedef struct _cl_command_queue * cl_command_queue; +typedef struct _cl_mem * cl_mem; +typedef struct _cl_program * cl_program; +typedef struct _cl_kernel * cl_kernel; +typedef struct _cl_event * cl_event; +typedef struct _cl_sampler * cl_sampler; + +typedef cl_uint cl_bool; /* WARNING! Unlike cl_ types in cl_platform.h, cl_bool is not guaranteed to be the same size as the bool in kernels. */ +typedef cl_ulong cl_bitfield; +typedef cl_bitfield cl_device_type; +typedef cl_uint cl_platform_info; +typedef cl_uint cl_device_info; +typedef cl_bitfield cl_device_fp_config; +typedef cl_uint cl_device_mem_cache_type; +typedef cl_uint cl_device_local_mem_type; +typedef cl_bitfield cl_device_exec_capabilities; +typedef cl_bitfield cl_command_queue_properties; +typedef intptr_t cl_device_partition_property; +typedef cl_bitfield cl_device_affinity_domain; + +typedef intptr_t cl_context_properties; +typedef cl_uint cl_context_info; +typedef cl_uint cl_command_queue_info; +typedef cl_uint cl_channel_order; +typedef cl_uint cl_channel_type; +typedef cl_bitfield cl_mem_flags; +typedef cl_uint cl_mem_object_type; +typedef cl_uint cl_mem_info; +typedef cl_bitfield cl_mem_migration_flags; +typedef cl_uint cl_image_info; +typedef cl_uint cl_buffer_create_type; +typedef cl_uint cl_addressing_mode; +typedef cl_uint cl_filter_mode; +typedef cl_uint cl_sampler_info; +typedef cl_bitfield cl_map_flags; +typedef cl_uint cl_program_info; +typedef cl_uint cl_program_build_info; +typedef cl_uint cl_program_binary_type; +typedef cl_int cl_build_status; +typedef cl_uint cl_kernel_info; +typedef cl_uint cl_kernel_arg_info; +typedef cl_uint cl_kernel_arg_address_qualifier; +typedef cl_uint cl_kernel_arg_access_qualifier; +typedef cl_bitfield cl_kernel_arg_type_qualifier; +typedef cl_uint cl_kernel_work_group_info; +typedef cl_uint cl_event_info; +typedef cl_uint cl_command_type; +typedef cl_uint cl_profiling_info; + + +typedef struct _cl_image_format { + cl_channel_order image_channel_order; + cl_channel_type image_channel_data_type; +} cl_image_format; + +typedef struct _cl_image_desc { + cl_mem_object_type image_type; + size_t image_width; + size_t image_height; + size_t image_depth; + size_t image_array_size; + size_t image_row_pitch; + size_t image_slice_pitch; + cl_uint num_mip_levels; + cl_uint num_samples; + cl_mem buffer; +} cl_image_desc; + +typedef struct _cl_buffer_region { + size_t origin; + size_t size; +} cl_buffer_region; + + +/******************************************************************************/ + +/* Error Codes */ +#define CL_SUCCESS 0 +#define CL_DEVICE_NOT_FOUND -1 +#define CL_DEVICE_NOT_AVAILABLE -2 +#define CL_COMPILER_NOT_AVAILABLE -3 +#define CL_MEM_OBJECT_ALLOCATION_FAILURE -4 +#define CL_OUT_OF_RESOURCES -5 +#define CL_OUT_OF_HOST_MEMORY -6 +#define CL_PROFILING_INFO_NOT_AVAILABLE -7 +#define CL_MEM_COPY_OVERLAP -8 +#define CL_IMAGE_FORMAT_MISMATCH -9 +#define CL_IMAGE_FORMAT_NOT_SUPPORTED -10 +#define CL_BUILD_PROGRAM_FAILURE -11 +#define CL_MAP_FAILURE -12 +#define CL_MISALIGNED_SUB_BUFFER_OFFSET -13 +#define CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST -14 +#define CL_COMPILE_PROGRAM_FAILURE -15 +#define CL_LINKER_NOT_AVAILABLE -16 +#define CL_LINK_PROGRAM_FAILURE -17 +#define CL_DEVICE_PARTITION_FAILED -18 +#define CL_KERNEL_ARG_INFO_NOT_AVAILABLE -19 + +#define CL_INVALID_VALUE -30 +#define CL_INVALID_DEVICE_TYPE -31 +#define CL_INVALID_PLATFORM -32 +#define CL_INVALID_DEVICE -33 +#define CL_INVALID_CONTEXT -34 +#define CL_INVALID_QUEUE_PROPERTIES -35 +#define CL_INVALID_COMMAND_QUEUE -36 +#define CL_INVALID_HOST_PTR -37 +#define CL_INVALID_MEM_OBJECT -38 +#define CL_INVALID_IMAGE_FORMAT_DESCRIPTOR -39 +#define CL_INVALID_IMAGE_SIZE -40 +#define CL_INVALID_SAMPLER -41 +#define CL_INVALID_BINARY -42 +#define CL_INVALID_BUILD_OPTIONS -43 +#define CL_INVALID_PROGRAM -44 +#define CL_INVALID_PROGRAM_EXECUTABLE -45 +#define CL_INVALID_KERNEL_NAME -46 +#define CL_INVALID_KERNEL_DEFINITION -47 +#define CL_INVALID_KERNEL -48 +#define CL_INVALID_ARG_INDEX -49 +#define CL_INVALID_ARG_VALUE -50 +#define CL_INVALID_ARG_SIZE -51 +#define CL_INVALID_KERNEL_ARGS -52 +#define CL_INVALID_WORK_DIMENSION -53 +#define CL_INVALID_WORK_GROUP_SIZE -54 +#define CL_INVALID_WORK_ITEM_SIZE -55 +#define CL_INVALID_GLOBAL_OFFSET -56 +#define CL_INVALID_EVENT_WAIT_LIST -57 +#define CL_INVALID_EVENT -58 +#define CL_INVALID_OPERATION -59 +#define CL_INVALID_GL_OBJECT -60 +#define CL_INVALID_BUFFER_SIZE -61 +#define CL_INVALID_MIP_LEVEL -62 +#define CL_INVALID_GLOBAL_WORK_SIZE -63 +#define CL_INVALID_PROPERTY -64 +#define CL_INVALID_IMAGE_DESCRIPTOR -65 +#define CL_INVALID_COMPILER_OPTIONS -66 +#define CL_INVALID_LINKER_OPTIONS -67 +#define CL_INVALID_DEVICE_PARTITION_COUNT -68 + +/* OpenCL Version */ +#define CL_VERSION_1_0 1 +#define CL_VERSION_1_1 1 +#define CL_VERSION_1_2 1 + +/* cl_bool */ +#define CL_FALSE 0 +#define CL_TRUE 1 +#define CL_BLOCKING CL_TRUE +#define CL_NON_BLOCKING CL_FALSE + +/* cl_platform_info */ +#define CL_PLATFORM_PROFILE 0x0900 +#define CL_PLATFORM_VERSION 0x0901 +#define CL_PLATFORM_NAME 0x0902 +#define CL_PLATFORM_VENDOR 0x0903 +#define CL_PLATFORM_EXTENSIONS 0x0904 + +/* cl_device_type - bitfield */ +#define CL_DEVICE_TYPE_DEFAULT (1 << 0) +#define CL_DEVICE_TYPE_CPU (1 << 1) +#define CL_DEVICE_TYPE_GPU (1 << 2) +#define CL_DEVICE_TYPE_ACCELERATOR (1 << 3) +#define CL_DEVICE_TYPE_CUSTOM (1 << 4) +#define CL_DEVICE_TYPE_ALL 0xFFFFFFFF + +/* cl_device_info */ +#define CL_DEVICE_TYPE 0x1000 +#define CL_DEVICE_VENDOR_ID 0x1001 +#define CL_DEVICE_MAX_COMPUTE_UNITS 0x1002 +#define CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS 0x1003 +#define CL_DEVICE_MAX_WORK_GROUP_SIZE 0x1004 +#define CL_DEVICE_MAX_WORK_ITEM_SIZES 0x1005 +#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR 0x1006 +#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT 0x1007 +#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT 0x1008 +#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG 0x1009 +#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT 0x100A +#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE 0x100B +#define CL_DEVICE_MAX_CLOCK_FREQUENCY 0x100C +#define CL_DEVICE_ADDRESS_BITS 0x100D +#define CL_DEVICE_MAX_READ_IMAGE_ARGS 0x100E +#define CL_DEVICE_MAX_WRITE_IMAGE_ARGS 0x100F +#define CL_DEVICE_MAX_MEM_ALLOC_SIZE 0x1010 +#define CL_DEVICE_IMAGE2D_MAX_WIDTH 0x1011 +#define CL_DEVICE_IMAGE2D_MAX_HEIGHT 0x1012 +#define CL_DEVICE_IMAGE3D_MAX_WIDTH 0x1013 +#define CL_DEVICE_IMAGE3D_MAX_HEIGHT 0x1014 +#define CL_DEVICE_IMAGE3D_MAX_DEPTH 0x1015 +#define CL_DEVICE_IMAGE_SUPPORT 0x1016 +#define CL_DEVICE_MAX_PARAMETER_SIZE 0x1017 +#define CL_DEVICE_MAX_SAMPLERS 0x1018 +#define CL_DEVICE_MEM_BASE_ADDR_ALIGN 0x1019 +#define CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE 0x101A +#define CL_DEVICE_SINGLE_FP_CONFIG 0x101B +#define CL_DEVICE_GLOBAL_MEM_CACHE_TYPE 0x101C +#define CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE 0x101D +#define CL_DEVICE_GLOBAL_MEM_CACHE_SIZE 0x101E +#define CL_DEVICE_GLOBAL_MEM_SIZE 0x101F +#define CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE 0x1020 +#define CL_DEVICE_MAX_CONSTANT_ARGS 0x1021 +#define CL_DEVICE_LOCAL_MEM_TYPE 0x1022 +#define CL_DEVICE_LOCAL_MEM_SIZE 0x1023 +#define CL_DEVICE_ERROR_CORRECTION_SUPPORT 0x1024 +#define CL_DEVICE_PROFILING_TIMER_RESOLUTION 0x1025 +#define CL_DEVICE_ENDIAN_LITTLE 0x1026 +#define CL_DEVICE_AVAILABLE 0x1027 +#define CL_DEVICE_COMPILER_AVAILABLE 0x1028 +#define CL_DEVICE_EXECUTION_CAPABILITIES 0x1029 +#define CL_DEVICE_QUEUE_PROPERTIES 0x102A +#define CL_DEVICE_NAME 0x102B +#define CL_DEVICE_VENDOR 0x102C +#define CL_DRIVER_VERSION 0x102D +#define CL_DEVICE_PROFILE 0x102E +#define CL_DEVICE_VERSION 0x102F +#define CL_DEVICE_EXTENSIONS 0x1030 +#define CL_DEVICE_PLATFORM 0x1031 +#define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032 +/* 0x1033 reserved for CL_DEVICE_HALF_FP_CONFIG */ +#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF 0x1034 +#define CL_DEVICE_HOST_UNIFIED_MEMORY 0x1035 +#define CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR 0x1036 +#define CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT 0x1037 +#define CL_DEVICE_NATIVE_VECTOR_WIDTH_INT 0x1038 +#define CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG 0x1039 +#define CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT 0x103A +#define CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE 0x103B +#define CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF 0x103C +#define CL_DEVICE_OPENCL_C_VERSION 0x103D +#define CL_DEVICE_LINKER_AVAILABLE 0x103E +#define CL_DEVICE_BUILT_IN_KERNELS 0x103F +#define CL_DEVICE_IMAGE_MAX_BUFFER_SIZE 0x1040 +#define CL_DEVICE_IMAGE_MAX_ARRAY_SIZE 0x1041 +#define CL_DEVICE_PARENT_DEVICE 0x1042 +#define CL_DEVICE_PARTITION_MAX_SUB_DEVICES 0x1043 +#define CL_DEVICE_PARTITION_PROPERTIES 0x1044 +#define CL_DEVICE_PARTITION_AFFINITY_DOMAIN 0x1045 +#define CL_DEVICE_PARTITION_TYPE 0x1046 +#define CL_DEVICE_REFERENCE_COUNT 0x1047 +#define CL_DEVICE_PREFERRED_INTEROP_USER_SYNC 0x1048 +#define CL_DEVICE_PRINTF_BUFFER_SIZE 0x1049 +#define CL_DEVICE_IMAGE_PITCH_ALIGNMENT 0x104A +#define CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT 0x104B + +/* cl_device_fp_config - bitfield */ +#define CL_FP_DENORM (1 << 0) +#define CL_FP_INF_NAN (1 << 1) +#define CL_FP_ROUND_TO_NEAREST (1 << 2) +#define CL_FP_ROUND_TO_ZERO (1 << 3) +#define CL_FP_ROUND_TO_INF (1 << 4) +#define CL_FP_FMA (1 << 5) +#define CL_FP_SOFT_FLOAT (1 << 6) +#define CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT (1 << 7) + +/* cl_device_mem_cache_type */ +#define CL_NONE 0x0 +#define CL_READ_ONLY_CACHE 0x1 +#define CL_READ_WRITE_CACHE 0x2 + +/* cl_device_local_mem_type */ +#define CL_LOCAL 0x1 +#define CL_GLOBAL 0x2 + +/* cl_device_exec_capabilities - bitfield */ +#define CL_EXEC_KERNEL (1 << 0) +#define CL_EXEC_NATIVE_KERNEL (1 << 1) + +/* cl_command_queue_properties - bitfield */ +#define CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE (1 << 0) +#define CL_QUEUE_PROFILING_ENABLE (1 << 1) + +/* cl_context_info */ +#define CL_CONTEXT_REFERENCE_COUNT 0x1080 +#define CL_CONTEXT_DEVICES 0x1081 +#define CL_CONTEXT_PROPERTIES 0x1082 +#define CL_CONTEXT_NUM_DEVICES 0x1083 + +/* cl_context_properties */ +#define CL_CONTEXT_PLATFORM 0x1084 +#define CL_CONTEXT_INTEROP_USER_SYNC 0x1085 + +/* cl_device_partition_property */ +#define CL_DEVICE_PARTITION_EQUALLY 0x1086 +#define CL_DEVICE_PARTITION_BY_COUNTS 0x1087 +#define CL_DEVICE_PARTITION_BY_COUNTS_LIST_END 0x0 +#define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN 0x1088 + +/* cl_device_affinity_domain */ +#define CL_DEVICE_AFFINITY_DOMAIN_NUMA (1 << 0) +#define CL_DEVICE_AFFINITY_DOMAIN_L4_CACHE (1 << 1) +#define CL_DEVICE_AFFINITY_DOMAIN_L3_CACHE (1 << 2) +#define CL_DEVICE_AFFINITY_DOMAIN_L2_CACHE (1 << 3) +#define CL_DEVICE_AFFINITY_DOMAIN_L1_CACHE (1 << 4) +#define CL_DEVICE_AFFINITY_DOMAIN_NEXT_PARTITIONABLE (1 << 5) + +/* cl_command_queue_info */ +#define CL_QUEUE_CONTEXT 0x1090 +#define CL_QUEUE_DEVICE 0x1091 +#define CL_QUEUE_REFERENCE_COUNT 0x1092 +#define CL_QUEUE_PROPERTIES 0x1093 + +/* cl_mem_flags - bitfield */ +#define CL_MEM_READ_WRITE (1 << 0) +#define CL_MEM_WRITE_ONLY (1 << 1) +#define CL_MEM_READ_ONLY (1 << 2) +#define CL_MEM_USE_HOST_PTR (1 << 3) +#define CL_MEM_ALLOC_HOST_PTR (1 << 4) +#define CL_MEM_COPY_HOST_PTR (1 << 5) +/* reserved (1 << 6) */ +#define CL_MEM_HOST_WRITE_ONLY (1 << 7) +#define CL_MEM_HOST_READ_ONLY (1 << 8) +#define CL_MEM_HOST_NO_ACCESS (1 << 9) + +/* cl_mem_migration_flags - bitfield */ +#define CL_MIGRATE_MEM_OBJECT_HOST (1 << 0) +#define CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED (1 << 1) + +/* cl_channel_order */ +#define CL_R 0x10B0 +#define CL_A 0x10B1 +#define CL_RG 0x10B2 +#define CL_RA 0x10B3 +#define CL_RGB 0x10B4 +#define CL_RGBA 0x10B5 +#define CL_BGRA 0x10B6 +#define CL_ARGB 0x10B7 +#define CL_INTENSITY 0x10B8 +#define CL_LUMINANCE 0x10B9 +#define CL_Rx 0x10BA +#define CL_RGx 0x10BB +#define CL_RGBx 0x10BC +#define CL_DEPTH 0x10BD +#define CL_DEPTH_STENCIL 0x10BE + +/* cl_channel_type */ +#define CL_SNORM_INT8 0x10D0 +#define CL_SNORM_INT16 0x10D1 +#define CL_UNORM_INT8 0x10D2 +#define CL_UNORM_INT16 0x10D3 +#define CL_UNORM_SHORT_565 0x10D4 +#define CL_UNORM_SHORT_555 0x10D5 +#define CL_UNORM_INT_101010 0x10D6 +#define CL_SIGNED_INT8 0x10D7 +#define CL_SIGNED_INT16 0x10D8 +#define CL_SIGNED_INT32 0x10D9 +#define CL_UNSIGNED_INT8 0x10DA +#define CL_UNSIGNED_INT16 0x10DB +#define CL_UNSIGNED_INT32 0x10DC +#define CL_HALF_FLOAT 0x10DD +#define CL_FLOAT 0x10DE +#define CL_UNORM_INT24 0x10DF + +/* cl_mem_object_type */ +#define CL_MEM_OBJECT_BUFFER 0x10F0 +#define CL_MEM_OBJECT_IMAGE2D 0x10F1 +#define CL_MEM_OBJECT_IMAGE3D 0x10F2 +#define CL_MEM_OBJECT_IMAGE2D_ARRAY 0x10F3 +#define CL_MEM_OBJECT_IMAGE1D 0x10F4 +#define CL_MEM_OBJECT_IMAGE1D_ARRAY 0x10F5 +#define CL_MEM_OBJECT_IMAGE1D_BUFFER 0x10F6 + +/* cl_mem_info */ +#define CL_MEM_TYPE 0x1100 +#define CL_MEM_FLAGS 0x1101 +#define CL_MEM_SIZE 0x1102 +#define CL_MEM_HOST_PTR 0x1103 +#define CL_MEM_MAP_COUNT 0x1104 +#define CL_MEM_REFERENCE_COUNT 0x1105 +#define CL_MEM_CONTEXT 0x1106 +#define CL_MEM_ASSOCIATED_MEMOBJECT 0x1107 +#define CL_MEM_OFFSET 0x1108 + +/* cl_image_info */ +#define CL_IMAGE_FORMAT 0x1110 +#define CL_IMAGE_ELEMENT_SIZE 0x1111 +#define CL_IMAGE_ROW_PITCH 0x1112 +#define CL_IMAGE_SLICE_PITCH 0x1113 +#define CL_IMAGE_WIDTH 0x1114 +#define CL_IMAGE_HEIGHT 0x1115 +#define CL_IMAGE_DEPTH 0x1116 +#define CL_IMAGE_ARRAY_SIZE 0x1117 +#define CL_IMAGE_BUFFER 0x1118 +#define CL_IMAGE_NUM_MIP_LEVELS 0x1119 +#define CL_IMAGE_NUM_SAMPLES 0x111A + +/* cl_addressing_mode */ +#define CL_ADDRESS_NONE 0x1130 +#define CL_ADDRESS_CLAMP_TO_EDGE 0x1131 +#define CL_ADDRESS_CLAMP 0x1132 +#define CL_ADDRESS_REPEAT 0x1133 +#define CL_ADDRESS_MIRRORED_REPEAT 0x1134 + +/* cl_filter_mode */ +#define CL_FILTER_NEAREST 0x1140 +#define CL_FILTER_LINEAR 0x1141 + +/* cl_sampler_info */ +#define CL_SAMPLER_REFERENCE_COUNT 0x1150 +#define CL_SAMPLER_CONTEXT 0x1151 +#define CL_SAMPLER_NORMALIZED_COORDS 0x1152 +#define CL_SAMPLER_ADDRESSING_MODE 0x1153 +#define CL_SAMPLER_FILTER_MODE 0x1154 + +/* cl_map_flags - bitfield */ +#define CL_MAP_READ (1 << 0) +#define CL_MAP_WRITE (1 << 1) +#define CL_MAP_WRITE_INVALIDATE_REGION (1 << 2) + +/* cl_program_info */ +#define CL_PROGRAM_REFERENCE_COUNT 0x1160 +#define CL_PROGRAM_CONTEXT 0x1161 +#define CL_PROGRAM_NUM_DEVICES 0x1162 +#define CL_PROGRAM_DEVICES 0x1163 +#define CL_PROGRAM_SOURCE 0x1164 +#define CL_PROGRAM_BINARY_SIZES 0x1165 +#define CL_PROGRAM_BINARIES 0x1166 +#define CL_PROGRAM_NUM_KERNELS 0x1167 +#define CL_PROGRAM_KERNEL_NAMES 0x1168 + +/* cl_program_build_info */ +#define CL_PROGRAM_BUILD_STATUS 0x1181 +#define CL_PROGRAM_BUILD_OPTIONS 0x1182 +#define CL_PROGRAM_BUILD_LOG 0x1183 +#define CL_PROGRAM_BINARY_TYPE 0x1184 + +/* cl_program_binary_type */ +#define CL_PROGRAM_BINARY_TYPE_NONE 0x0 +#define CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT 0x1 +#define CL_PROGRAM_BINARY_TYPE_LIBRARY 0x2 +#define CL_PROGRAM_BINARY_TYPE_EXECUTABLE 0x4 + +/* cl_build_status */ +#define CL_BUILD_SUCCESS 0 +#define CL_BUILD_NONE -1 +#define CL_BUILD_ERROR -2 +#define CL_BUILD_IN_PROGRESS -3 + +/* cl_kernel_info */ +#define CL_KERNEL_FUNCTION_NAME 0x1190 +#define CL_KERNEL_NUM_ARGS 0x1191 +#define CL_KERNEL_REFERENCE_COUNT 0x1192 +#define CL_KERNEL_CONTEXT 0x1193 +#define CL_KERNEL_PROGRAM 0x1194 +#define CL_KERNEL_ATTRIBUTES 0x1195 + +/* cl_kernel_arg_info */ +#define CL_KERNEL_ARG_ADDRESS_QUALIFIER 0x1196 +#define CL_KERNEL_ARG_ACCESS_QUALIFIER 0x1197 +#define CL_KERNEL_ARG_TYPE_NAME 0x1198 +#define CL_KERNEL_ARG_TYPE_QUALIFIER 0x1199 +#define CL_KERNEL_ARG_NAME 0x119A + +/* cl_kernel_arg_address_qualifier */ +#define CL_KERNEL_ARG_ADDRESS_GLOBAL 0x119B +#define CL_KERNEL_ARG_ADDRESS_LOCAL 0x119C +#define CL_KERNEL_ARG_ADDRESS_CONSTANT 0x119D +#define CL_KERNEL_ARG_ADDRESS_PRIVATE 0x119E + +/* cl_kernel_arg_access_qualifier */ +#define CL_KERNEL_ARG_ACCESS_READ_ONLY 0x11A0 +#define CL_KERNEL_ARG_ACCESS_WRITE_ONLY 0x11A1 +#define CL_KERNEL_ARG_ACCESS_READ_WRITE 0x11A2 +#define CL_KERNEL_ARG_ACCESS_NONE 0x11A3 + +/* cl_kernel_arg_type_qualifer */ +#define CL_KERNEL_ARG_TYPE_NONE 0 +#define CL_KERNEL_ARG_TYPE_CONST (1 << 0) +#define CL_KERNEL_ARG_TYPE_RESTRICT (1 << 1) +#define CL_KERNEL_ARG_TYPE_VOLATILE (1 << 2) + +/* cl_kernel_work_group_info */ +#define CL_KERNEL_WORK_GROUP_SIZE 0x11B0 +#define CL_KERNEL_COMPILE_WORK_GROUP_SIZE 0x11B1 +#define CL_KERNEL_LOCAL_MEM_SIZE 0x11B2 +#define CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE 0x11B3 +#define CL_KERNEL_PRIVATE_MEM_SIZE 0x11B4 +#define CL_KERNEL_GLOBAL_WORK_SIZE 0x11B5 + +/* cl_event_info */ +#define CL_EVENT_COMMAND_QUEUE 0x11D0 +#define CL_EVENT_COMMAND_TYPE 0x11D1 +#define CL_EVENT_REFERENCE_COUNT 0x11D2 +#define CL_EVENT_COMMAND_EXECUTION_STATUS 0x11D3 +#define CL_EVENT_CONTEXT 0x11D4 + +/* cl_command_type */ +#define CL_COMMAND_NDRANGE_KERNEL 0x11F0 +#define CL_COMMAND_TASK 0x11F1 +#define CL_COMMAND_NATIVE_KERNEL 0x11F2 +#define CL_COMMAND_READ_BUFFER 0x11F3 +#define CL_COMMAND_WRITE_BUFFER 0x11F4 +#define CL_COMMAND_COPY_BUFFER 0x11F5 +#define CL_COMMAND_READ_IMAGE 0x11F6 +#define CL_COMMAND_WRITE_IMAGE 0x11F7 +#define CL_COMMAND_COPY_IMAGE 0x11F8 +#define CL_COMMAND_COPY_IMAGE_TO_BUFFER 0x11F9 +#define CL_COMMAND_COPY_BUFFER_TO_IMAGE 0x11FA +#define CL_COMMAND_MAP_BUFFER 0x11FB +#define CL_COMMAND_MAP_IMAGE 0x11FC +#define CL_COMMAND_UNMAP_MEM_OBJECT 0x11FD +#define CL_COMMAND_MARKER 0x11FE +#define CL_COMMAND_ACQUIRE_GL_OBJECTS 0x11FF +#define CL_COMMAND_RELEASE_GL_OBJECTS 0x1200 +#define CL_COMMAND_READ_BUFFER_RECT 0x1201 +#define CL_COMMAND_WRITE_BUFFER_RECT 0x1202 +#define CL_COMMAND_COPY_BUFFER_RECT 0x1203 +#define CL_COMMAND_USER 0x1204 +#define CL_COMMAND_BARRIER 0x1205 +#define CL_COMMAND_MIGRATE_MEM_OBJECTS 0x1206 +#define CL_COMMAND_FILL_BUFFER 0x1207 +#define CL_COMMAND_FILL_IMAGE 0x1208 + +/* command execution status */ +#define CL_COMPLETE 0x0 +#define CL_RUNNING 0x1 +#define CL_SUBMITTED 0x2 +#define CL_QUEUED 0x3 + +/* cl_buffer_create_type */ +#define CL_BUFFER_CREATE_TYPE_REGION 0x1220 + +/* cl_profiling_info */ +#define CL_PROFILING_COMMAND_QUEUED 0x1280 +#define CL_PROFILING_COMMAND_SUBMIT 0x1281 +#define CL_PROFILING_COMMAND_START 0x1282 +#define CL_PROFILING_COMMAND_END 0x1283 + +/********************************************************************************************************/ + +/* Platform API */ +extern CL_API_ENTRY cl_int CL_API_CALL +clGetPlatformIDs(cl_uint /* num_entries */, + cl_platform_id * /* platforms */, + cl_uint * /* num_platforms */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetPlatformInfo(cl_platform_id /* platform */, + cl_platform_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; + +/* Device APIs */ +extern CL_API_ENTRY cl_int CL_API_CALL +clGetDeviceIDs(cl_platform_id /* platform */, + cl_device_type /* device_type */, + cl_uint /* num_entries */, + cl_device_id * /* devices */, + cl_uint * /* num_devices */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetDeviceInfo(cl_device_id /* device */, + cl_device_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clCreateSubDevices(cl_device_id /* in_device */, + const cl_device_partition_property * /* properties */, + cl_uint /* num_devices */, + cl_device_id * /* out_devices */, + cl_uint * /* num_devices_ret */) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainDevice(cl_device_id /* device */) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseDevice(cl_device_id /* device */) CL_API_SUFFIX__VERSION_1_2; + +/* Context APIs */ +extern CL_API_ENTRY cl_context CL_API_CALL +clCreateContext(const cl_context_properties * /* properties */, + cl_uint /* num_devices */, + const cl_device_id * /* devices */, + void (CL_CALLBACK * /* pfn_notify */)(const char *, const void *, size_t, void *), + void * /* user_data */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_context CL_API_CALL +clCreateContextFromType(const cl_context_properties * /* properties */, + cl_device_type /* device_type */, + void (CL_CALLBACK * /* pfn_notify*/ )(const char *, const void *, size_t, void *), + void * /* user_data */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseContext(cl_context /* context */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetContextInfo(cl_context /* context */, + cl_context_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; + +/* Command Queue APIs */ +extern CL_API_ENTRY cl_command_queue CL_API_CALL +clCreateCommandQueue(cl_context /* context */, + cl_device_id /* device */, + cl_command_queue_properties /* properties */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseCommandQueue(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetCommandQueueInfo(cl_command_queue /* command_queue */, + cl_command_queue_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; + +#ifdef CL_USE_DEPRECATED_OPENCL_1_0_APIS +#ifndef NVCL_SUPPRESS_USE_DEPRECATED_OPENCL_1_0_APIS_WARNING +#warning CL_USE_DEPRECATED_OPENCL_1_0_APIS is defined. These APIs are unsupported and untested in OpenCL 1.1! +#endif +/* + * WARNING: + * This API introduces mutable state into the OpenCL implementation. It has been REMOVED + * to better facilitate thread safety. The 1.0 API is not thread safe. It is not tested by the + * OpenCL 1.1 conformance test, and consequently may not work or may not work dependably. + * It is likely to be non-performant. Use of this API is not advised. Use at your own risk. + * + * Software developers previously relying on this API are instructed to set the command queue + * properties when creating the queue, instead. + */ +extern CL_API_ENTRY cl_int CL_API_CALL +clSetCommandQueueProperty(cl_command_queue /* command_queue */, + cl_command_queue_properties /* properties */, + cl_bool /* enable */, + cl_command_queue_properties * /* old_properties */) CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED; +#endif /* CL_USE_DEPRECATED_OPENCL_1_0_APIS */ + +/* Memory Object APIs */ +extern CL_API_ENTRY cl_mem CL_API_CALL +clCreateBuffer(cl_context /* context */, + cl_mem_flags /* flags */, + size_t /* size */, + void * /* host_ptr */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_mem CL_API_CALL +clCreateSubBuffer(cl_mem /* buffer */, + cl_mem_flags /* flags */, + cl_buffer_create_type /* buffer_create_type */, + const void * /* buffer_create_info */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1; + +extern CL_API_ENTRY cl_mem CL_API_CALL +clCreateImage(cl_context /* context */, + cl_mem_flags /* flags */, + const cl_image_format * /* image_format */, + const cl_image_desc * /* image_desc */, + void * /* host_ptr */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseMemObject(cl_mem /* memobj */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetSupportedImageFormats(cl_context /* context */, + cl_mem_flags /* flags */, + cl_mem_object_type /* image_type */, + cl_uint /* num_entries */, + cl_image_format * /* image_formats */, + cl_uint * /* num_image_formats */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetMemObjectInfo(cl_mem /* memobj */, + cl_mem_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetImageInfo(cl_mem /* image */, + cl_image_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clSetMemObjectDestructorCallback( cl_mem /* memobj */, + void (CL_CALLBACK * /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/), + void * /*user_data */ ) CL_API_SUFFIX__VERSION_1_1; + +/* Sampler APIs */ +extern CL_API_ENTRY cl_sampler CL_API_CALL +clCreateSampler(cl_context /* context */, + cl_bool /* normalized_coords */, + cl_addressing_mode /* addressing_mode */, + cl_filter_mode /* filter_mode */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseSampler(cl_sampler /* sampler */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetSamplerInfo(cl_sampler /* sampler */, + cl_sampler_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; + +/* Program Object APIs */ +extern CL_API_ENTRY cl_program CL_API_CALL +clCreateProgramWithSource(cl_context /* context */, + cl_uint /* count */, + const char ** /* strings */, + const size_t * /* lengths */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_program CL_API_CALL +clCreateProgramWithBinary(cl_context /* context */, + cl_uint /* num_devices */, + const cl_device_id * /* device_list */, + const size_t * /* lengths */, + const unsigned char ** /* binaries */, + cl_int * /* binary_status */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_program CL_API_CALL +clCreateProgramWithBuiltInKernels(cl_context /* context */, + cl_uint /* num_devices */, + const cl_device_id * /* device_list */, + const char * /* kernel_names */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseProgram(cl_program /* program */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clBuildProgram(cl_program /* program */, + cl_uint /* num_devices */, + const cl_device_id * /* device_list */, + const char * /* options */, + void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */), + void * /* user_data */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clCompileProgram(cl_program /* program */, + cl_uint /* num_devices */, + const cl_device_id * /* device_list */, + const char * /* options */, + cl_uint /* num_input_headers */, + const cl_program * /* input_headers */, + const char ** /* header_include_names */, + void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */), + void * /* user_data */) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_program CL_API_CALL +clLinkProgram(cl_context /* context */, + cl_uint /* num_devices */, + const cl_device_id * /* device_list */, + const char * /* options */, + cl_uint /* num_input_programs */, + const cl_program * /* input_programs */, + void (CL_CALLBACK * /* pfn_notify */)(cl_program /* program */, void * /* user_data */), + void * /* user_data */, + cl_int * /* errcode_ret */ ) CL_API_SUFFIX__VERSION_1_2; + + +extern CL_API_ENTRY cl_int CL_API_CALL +clUnloadPlatformCompiler(cl_platform_id /* platform */) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetProgramInfo(cl_program /* program */, + cl_program_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetProgramBuildInfo(cl_program /* program */, + cl_device_id /* device */, + cl_program_build_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; + +/* Kernel Object APIs */ +extern CL_API_ENTRY cl_kernel CL_API_CALL +clCreateKernel(cl_program /* program */, + const char * /* kernel_name */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clCreateKernelsInProgram(cl_program /* program */, + cl_uint /* num_kernels */, + cl_kernel * /* kernels */, + cl_uint * /* num_kernels_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseKernel(cl_kernel /* kernel */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clSetKernelArg(cl_kernel /* kernel */, + cl_uint /* arg_index */, + size_t /* arg_size */, + const void * /* arg_value */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetKernelInfo(cl_kernel /* kernel */, + cl_kernel_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetKernelArgInfo(cl_kernel /* kernel */, + cl_uint /* arg_indx */, + cl_kernel_arg_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetKernelWorkGroupInfo(cl_kernel /* kernel */, + cl_device_id /* device */, + cl_kernel_work_group_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; + +/* Event Object APIs */ +extern CL_API_ENTRY cl_int CL_API_CALL +clWaitForEvents(cl_uint /* num_events */, + const cl_event * /* event_list */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetEventInfo(cl_event /* event */, + cl_event_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_event CL_API_CALL +clCreateUserEvent(cl_context /* context */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_1; + +extern CL_API_ENTRY cl_int CL_API_CALL +clRetainEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clReleaseEvent(cl_event /* event */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clSetUserEventStatus(cl_event /* event */, + cl_int /* execution_status */) CL_API_SUFFIX__VERSION_1_1; + +extern CL_API_ENTRY cl_int CL_API_CALL +clSetEventCallback( cl_event /* event */, + cl_int /* command_exec_callback_type */, + void (CL_CALLBACK * /* pfn_notify */)(cl_event, cl_int, void *), + void * /* user_data */) CL_API_SUFFIX__VERSION_1_1; + +/* Profiling APIs */ +extern CL_API_ENTRY cl_int CL_API_CALL +clGetEventProfilingInfo(cl_event /* event */, + cl_profiling_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; + +/* Flush and Finish APIs */ +extern CL_API_ENTRY cl_int CL_API_CALL +clFlush(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clFinish(cl_command_queue /* command_queue */) CL_API_SUFFIX__VERSION_1_0; + +/* Enqueued Commands APIs */ +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueReadBuffer(cl_command_queue /* command_queue */, + cl_mem /* buffer */, + cl_bool /* blocking_read */, + size_t /* offset */, + size_t /* size */, + void * /* ptr */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueReadBufferRect(cl_command_queue /* command_queue */, + cl_mem /* buffer */, + cl_bool /* blocking_read */, + const size_t * /* buffer_offset */, + const size_t * /* host_offset */, + const size_t * /* region */, + size_t /* buffer_row_pitch */, + size_t /* buffer_slice_pitch */, + size_t /* host_row_pitch */, + size_t /* host_slice_pitch */, + void * /* ptr */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueWriteBuffer(cl_command_queue /* command_queue */, + cl_mem /* buffer */, + cl_bool /* blocking_write */, + size_t /* offset */, + size_t /* size */, + const void * /* ptr */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueWriteBufferRect(cl_command_queue /* command_queue */, + cl_mem /* buffer */, + cl_bool /* blocking_write */, + const size_t * /* buffer_offset */, + const size_t * /* host_offset */, + const size_t * /* region */, + size_t /* buffer_row_pitch */, + size_t /* buffer_slice_pitch */, + size_t /* host_row_pitch */, + size_t /* host_slice_pitch */, + const void * /* ptr */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueFillBuffer(cl_command_queue /* command_queue */, + cl_mem /* buffer */, + const void * /* pattern */, + size_t /* pattern_size */, + size_t /* offset */, + size_t /* size */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueCopyBuffer(cl_command_queue /* command_queue */, + cl_mem /* src_buffer */, + cl_mem /* dst_buffer */, + size_t /* src_offset */, + size_t /* dst_offset */, + size_t /* size */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueCopyBufferRect(cl_command_queue /* command_queue */, + cl_mem /* src_buffer */, + cl_mem /* dst_buffer */, + const size_t * /* src_origin */, + const size_t * /* dst_origin */, + const size_t * /* region */, + size_t /* src_row_pitch */, + size_t /* src_slice_pitch */, + size_t /* dst_row_pitch */, + size_t /* dst_slice_pitch */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_1; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueReadImage(cl_command_queue /* command_queue */, + cl_mem /* image */, + cl_bool /* blocking_read */, + const size_t * /* origin[3] */, + const size_t * /* region[3] */, + size_t /* row_pitch */, + size_t /* slice_pitch */, + void * /* ptr */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueWriteImage(cl_command_queue /* command_queue */, + cl_mem /* image */, + cl_bool /* blocking_write */, + const size_t * /* origin[3] */, + const size_t * /* region[3] */, + size_t /* input_row_pitch */, + size_t /* input_slice_pitch */, + const void * /* ptr */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueFillImage(cl_command_queue /* command_queue */, + cl_mem /* image */, + const void * /* fill_color */, + const size_t * /* origin[3] */, + const size_t * /* region[3] */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueCopyImage(cl_command_queue /* command_queue */, + cl_mem /* src_image */, + cl_mem /* dst_image */, + const size_t * /* src_origin[3] */, + const size_t * /* dst_origin[3] */, + const size_t * /* region[3] */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueCopyImageToBuffer(cl_command_queue /* command_queue */, + cl_mem /* src_image */, + cl_mem /* dst_buffer */, + const size_t * /* src_origin[3] */, + const size_t * /* region[3] */, + size_t /* dst_offset */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueCopyBufferToImage(cl_command_queue /* command_queue */, + cl_mem /* src_buffer */, + cl_mem /* dst_image */, + size_t /* src_offset */, + const size_t * /* dst_origin[3] */, + const size_t * /* region[3] */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY void * CL_API_CALL +clEnqueueMapBuffer(cl_command_queue /* command_queue */, + cl_mem /* buffer */, + cl_bool /* blocking_map */, + cl_map_flags /* map_flags */, + size_t /* offset */, + size_t /* size */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY void * CL_API_CALL +clEnqueueMapImage(cl_command_queue /* command_queue */, + cl_mem /* image */, + cl_bool /* blocking_map */, + cl_map_flags /* map_flags */, + const size_t * /* origin[3] */, + const size_t * /* region[3] */, + size_t * /* image_row_pitch */, + size_t * /* image_slice_pitch */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueUnmapMemObject(cl_command_queue /* command_queue */, + cl_mem /* memobj */, + void * /* mapped_ptr */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueMigrateMemObjects(cl_command_queue /* command_queue */, + cl_uint /* num_mem_objects */, + const cl_mem * /* mem_objects */, + cl_mem_migration_flags /* flags */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueNDRangeKernel(cl_command_queue /* command_queue */, + cl_kernel /* kernel */, + cl_uint /* work_dim */, + const size_t * /* global_work_offset */, + const size_t * /* global_work_size */, + const size_t * /* local_work_size */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueTask(cl_command_queue /* command_queue */, + cl_kernel /* kernel */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueNativeKernel(cl_command_queue /* command_queue */, + void (CL_CALLBACK * /*user_func*/)(void *), + void * /* args */, + size_t /* cb_args */, + cl_uint /* num_mem_objects */, + const cl_mem * /* mem_list */, + const void ** /* args_mem_loc */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueMarkerWithWaitList(cl_command_queue /* command_queue */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueBarrierWithWaitList(cl_command_queue /* command_queue */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_2; + + +/* Extension function access + * + * Returns the extension function address for the given function name, + * or NULL if a valid function can not be found. The client must + * check to make sure the address is not NULL, before using or + * calling the returned function address. + */ +extern CL_API_ENTRY void * CL_API_CALL +clGetExtensionFunctionAddressForPlatform(cl_platform_id /* platform */, + const char * /* func_name */) CL_API_SUFFIX__VERSION_1_2; + + +/* Deprecated OpenCL 1.1 APIs */ +extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL +clCreateImage2D(cl_context /* context */, + cl_mem_flags /* flags */, + const cl_image_format * /* image_format */, + size_t /* image_width */, + size_t /* image_height */, + size_t /* image_row_pitch */, + void * /* host_ptr */, + cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; + +extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL +clCreateImage3D(cl_context /* context */, + cl_mem_flags /* flags */, + const cl_image_format * /* image_format */, + size_t /* image_width */, + size_t /* image_height */, + size_t /* image_depth */, + size_t /* image_row_pitch */, + size_t /* image_slice_pitch */, + void * /* host_ptr */, + cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; + +extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL +clEnqueueMarker(cl_command_queue /* command_queue */, + cl_event * /* event */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; + +extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL +clEnqueueWaitForEvents(cl_command_queue /* command_queue */, + cl_uint /* num_events */, + const cl_event * /* event_list */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; + +extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL +clEnqueueBarrier(cl_command_queue /* command_queue */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; + +extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL +clUnloadCompiler(void) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; + +extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED void * CL_API_CALL +clGetExtensionFunctionAddress(const char * /* func_name */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; + +#ifdef __cplusplus +} +#endif + +#endif /* __OPENCL_CL_H */ + diff --git a/include/lib/CL/cl.hpp b/include/lib/CL/cl.hpp new file mode 100644 index 0000000..3b456b7 --- /dev/null +++ b/include/lib/CL/cl.hpp @@ -0,0 +1,12906 @@ +/******************************************************************************* + * Copyright (c) 2008-2015 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + ******************************************************************************/ + +/*! \file + * + * \brief C++ bindings for OpenCL 1.0 (rev 48), OpenCL 1.1 (rev 33) and + * OpenCL 1.2 (rev 15) + * \author Benedict R. Gaster, Laurent Morichetti and Lee Howes + * + * Additions and fixes from: + * Brian Cole, March 3rd 2010 and April 2012 + * Matt Gruenke, April 2012. + * Bruce Merry, February 2013. + * Tom Deakin and Simon McIntosh-Smith, July 2013 + * + * \version 1.2.7 + * \date January 2015 + * + * Optional extension support + * + * cl + * cl_ext_device_fission + * #define USE_CL_DEVICE_FISSION + */ + +/*! \mainpage + * \section intro Introduction + * For many large applications C++ is the language of choice and so it seems + * reasonable to define C++ bindings for OpenCL. + * + * + * The interface is contained with a single C++ header file \em cl.hpp and all + * definitions are contained within the namespace \em cl. There is no additional + * requirement to include \em cl.h and to use either the C++ or original C + * bindings it is enough to simply include \em cl.hpp. + * + * The bindings themselves are lightweight and correspond closely to the + * underlying C API. Using the C++ bindings introduces no additional execution + * overhead. + * + * For detail documentation on the bindings see: + * + * The OpenCL C++ Wrapper API 1.2 (revision 09) + * http://www.khronos.org/registry/cl/specs/opencl-cplusplus-1.2.pdf + * + * \section example Example + * + * The following example shows a general use case for the C++ + * bindings, including support for the optional exception feature and + * also the supplied vector and string classes, see following sections for + * decriptions of these features. + * + * \code + * #define __CL_ENABLE_EXCEPTIONS + * + * #if defined(__APPLE__) || defined(__MACOSX) + * #include + * #else + * #include + * #endif + * #include + * #include + * #include + * + * const char * helloStr = "__kernel void " + * "hello(void) " + * "{ " + * " " + * "} "; + * + * int + * main(void) + * { + * cl_int err = CL_SUCCESS; + * try { + * + * std::vector platforms; + * cl::Platform::get(&platforms); + * if (platforms.size() == 0) { + * std::cout << "Platform size 0\n"; + * return -1; + * } + * + * cl_context_properties properties[] = + * { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[0])(), 0}; + * cl::Context context(CL_DEVICE_TYPE_CPU, properties); + * + * std::vector devices = context.getInfo(); + * + * cl::Program::Sources source(1, + * std::make_pair(helloStr,strlen(helloStr))); + * cl::Program program_ = cl::Program(context, source); + * program_.build(devices); + * + * cl::Kernel kernel(program_, "hello", &err); + * + * cl::Event event; + * cl::CommandQueue queue(context, devices[0], 0, &err); + * queue.enqueueNDRangeKernel( + * kernel, + * cl::NullRange, + * cl::NDRange(4,4), + * cl::NullRange, + * NULL, + * &event); + * + * event.wait(); + * } + * catch (cl::Error err) { + * std::cerr + * << "ERROR: " + * << err.what() + * << "(" + * << err.err() + * << ")" + * << std::endl; + * } + * + * return EXIT_SUCCESS; + * } + * + * \endcode + * + */ +#ifndef CL_HPP_ +#define CL_HPP_ + +#ifdef _WIN32 + +#include + +#if defined(USE_DX_INTEROP) +#include +#include +#endif +#endif // _WIN32 + +#if defined(_MSC_VER) +#include +#endif // _MSC_VER + +// +#if defined(USE_CL_DEVICE_FISSION) +#include +#endif + +#if defined(__APPLE__) || defined(__MACOSX) +#include +#else +#include +#endif // !__APPLE__ + +#if (_MSC_VER >= 1700) || (__cplusplus >= 201103L) +#define CL_HPP_RVALUE_REFERENCES_SUPPORTED +#define CL_HPP_CPP11_ATOMICS_SUPPORTED +#include +#endif + +#if (__cplusplus >= 201103L) +#define CL_HPP_NOEXCEPT noexcept +#else +#define CL_HPP_NOEXCEPT +#endif + + +// To avoid accidentally taking ownership of core OpenCL types +// such as cl_kernel constructors are made explicit +// under OpenCL 1.2 +#if defined(CL_VERSION_1_2) && !defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) +#define __CL_EXPLICIT_CONSTRUCTORS explicit +#else // #if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) +#define __CL_EXPLICIT_CONSTRUCTORS +#endif // #if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + +// Define deprecated prefixes and suffixes to ensure compilation +// in case they are not pre-defined +#if !defined(CL_EXT_PREFIX__VERSION_1_1_DEPRECATED) +#define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED +#endif // #if !defined(CL_EXT_PREFIX__VERSION_1_1_DEPRECATED) +#if !defined(CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED) +#define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED +#endif // #if !defined(CL_EXT_PREFIX__VERSION_1_1_DEPRECATED) + +#if !defined(CL_CALLBACK) +#define CL_CALLBACK +#endif //CL_CALLBACK + +#include +#include +#include + +#if defined(__CL_ENABLE_EXCEPTIONS) +#include +#endif // #if defined(__CL_ENABLE_EXCEPTIONS) + +#if !defined(__NO_STD_VECTOR) +#include +#endif + +#if !defined(__NO_STD_STRING) +#include +#endif + +#if defined(__ANDROID__) || defined(linux) || defined(__APPLE__) || defined(__MACOSX) +#include +#endif // linux + +#include + + +/*! \namespace cl + * + * \brief The OpenCL C++ bindings are defined within this namespace. + * + */ +namespace cl { + +class Memory; + +/** + * Deprecated APIs for 1.2 + */ +#if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) || (defined(CL_VERSION_1_1) && !defined(CL_VERSION_1_2)) +#define __INIT_CL_EXT_FCN_PTR(name) \ + if(!pfn_##name) { \ + pfn_##name = (PFN_##name) \ + clGetExtensionFunctionAddress(#name); \ + if(!pfn_##name) { \ + } \ + } +#endif // #if defined(CL_VERSION_1_1) + +#if defined(CL_VERSION_1_2) +#define __INIT_CL_EXT_FCN_PTR_PLATFORM(platform, name) \ + if(!pfn_##name) { \ + pfn_##name = (PFN_##name) \ + clGetExtensionFunctionAddressForPlatform(platform, #name); \ + if(!pfn_##name) { \ + } \ + } +#endif // #if defined(CL_VERSION_1_1) + +class Program; +class Device; +class Context; +class CommandQueue; +class Memory; +class Buffer; + +#if defined(__CL_ENABLE_EXCEPTIONS) +/*! \brief Exception class + * + * This may be thrown by API functions when __CL_ENABLE_EXCEPTIONS is defined. + */ +class Error : public std::exception +{ +private: + cl_int err_; + const char * errStr_; +public: + /*! \brief Create a new CL error exception for a given error code + * and corresponding message. + * + * \param err error code value. + * + * \param errStr a descriptive string that must remain in scope until + * handling of the exception has concluded. If set, it + * will be returned by what(). + */ + Error(cl_int err, const char * errStr = NULL) : err_(err), errStr_(errStr) + {} + + ~Error() throw() {} + + /*! \brief Get error string associated with exception + * + * \return A memory pointer to the error message string. + */ + virtual const char * what() const throw () + { + if (errStr_ == NULL) { + return "empty"; + } + else { + return errStr_; + } + } + + /*! \brief Get error code associated with exception + * + * \return The error code. + */ + cl_int err(void) const { return err_; } +}; + +#define __ERR_STR(x) #x +#else +#define __ERR_STR(x) NULL +#endif // __CL_ENABLE_EXCEPTIONS + + +namespace detail +{ +#if defined(__CL_ENABLE_EXCEPTIONS) +static inline cl_int errHandler ( + cl_int err, + const char * errStr = NULL) +{ + if (err != CL_SUCCESS) { + throw Error(err, errStr); + } + return err; +} +#else +static inline cl_int errHandler (cl_int err, const char * errStr = NULL) +{ + (void) errStr; // suppress unused variable warning + return err; +} +#endif // __CL_ENABLE_EXCEPTIONS +} + + + +//! \cond DOXYGEN_DETAIL +#if !defined(__CL_USER_OVERRIDE_ERROR_STRINGS) +#define __GET_DEVICE_INFO_ERR __ERR_STR(clGetDeviceInfo) +#define __GET_PLATFORM_INFO_ERR __ERR_STR(clGetPlatformInfo) +#define __GET_DEVICE_IDS_ERR __ERR_STR(clGetDeviceIDs) +#define __GET_PLATFORM_IDS_ERR __ERR_STR(clGetPlatformIDs) +#define __GET_CONTEXT_INFO_ERR __ERR_STR(clGetContextInfo) +#define __GET_EVENT_INFO_ERR __ERR_STR(clGetEventInfo) +#define __GET_EVENT_PROFILE_INFO_ERR __ERR_STR(clGetEventProfileInfo) +#define __GET_MEM_OBJECT_INFO_ERR __ERR_STR(clGetMemObjectInfo) +#define __GET_IMAGE_INFO_ERR __ERR_STR(clGetImageInfo) +#define __GET_SAMPLER_INFO_ERR __ERR_STR(clGetSamplerInfo) +#define __GET_KERNEL_INFO_ERR __ERR_STR(clGetKernelInfo) +#if defined(CL_VERSION_1_2) +#define __GET_KERNEL_ARG_INFO_ERR __ERR_STR(clGetKernelArgInfo) +#endif // #if defined(CL_VERSION_1_2) +#define __GET_KERNEL_WORK_GROUP_INFO_ERR __ERR_STR(clGetKernelWorkGroupInfo) +#define __GET_PROGRAM_INFO_ERR __ERR_STR(clGetProgramInfo) +#define __GET_PROGRAM_BUILD_INFO_ERR __ERR_STR(clGetProgramBuildInfo) +#define __GET_COMMAND_QUEUE_INFO_ERR __ERR_STR(clGetCommandQueueInfo) + +#define __CREATE_CONTEXT_ERR __ERR_STR(clCreateContext) +#define __CREATE_CONTEXT_FROM_TYPE_ERR __ERR_STR(clCreateContextFromType) +#define __GET_SUPPORTED_IMAGE_FORMATS_ERR __ERR_STR(clGetSupportedImageFormats) + +#define __CREATE_BUFFER_ERR __ERR_STR(clCreateBuffer) +#define __COPY_ERR __ERR_STR(cl::copy) +#define __CREATE_SUBBUFFER_ERR __ERR_STR(clCreateSubBuffer) +#define __CREATE_GL_BUFFER_ERR __ERR_STR(clCreateFromGLBuffer) +#define __CREATE_GL_RENDER_BUFFER_ERR __ERR_STR(clCreateFromGLBuffer) +#define __GET_GL_OBJECT_INFO_ERR __ERR_STR(clGetGLObjectInfo) +#if defined(CL_VERSION_1_2) +#define __CREATE_IMAGE_ERR __ERR_STR(clCreateImage) +#define __CREATE_GL_TEXTURE_ERR __ERR_STR(clCreateFromGLTexture) +#define __IMAGE_DIMENSION_ERR __ERR_STR(Incorrect image dimensions) +#endif // #if defined(CL_VERSION_1_2) +#define __CREATE_SAMPLER_ERR __ERR_STR(clCreateSampler) +#define __SET_MEM_OBJECT_DESTRUCTOR_CALLBACK_ERR __ERR_STR(clSetMemObjectDestructorCallback) + +#define __CREATE_USER_EVENT_ERR __ERR_STR(clCreateUserEvent) +#define __SET_USER_EVENT_STATUS_ERR __ERR_STR(clSetUserEventStatus) +#define __SET_EVENT_CALLBACK_ERR __ERR_STR(clSetEventCallback) +#define __WAIT_FOR_EVENTS_ERR __ERR_STR(clWaitForEvents) + +#define __CREATE_KERNEL_ERR __ERR_STR(clCreateKernel) +#define __SET_KERNEL_ARGS_ERR __ERR_STR(clSetKernelArg) +#define __CREATE_PROGRAM_WITH_SOURCE_ERR __ERR_STR(clCreateProgramWithSource) +#define __CREATE_PROGRAM_WITH_BINARY_ERR __ERR_STR(clCreateProgramWithBinary) +#if defined(CL_VERSION_1_2) +#define __CREATE_PROGRAM_WITH_BUILT_IN_KERNELS_ERR __ERR_STR(clCreateProgramWithBuiltInKernels) +#endif // #if defined(CL_VERSION_1_2) +#define __BUILD_PROGRAM_ERR __ERR_STR(clBuildProgram) +#if defined(CL_VERSION_1_2) +#define __COMPILE_PROGRAM_ERR __ERR_STR(clCompileProgram) +#define __LINK_PROGRAM_ERR __ERR_STR(clLinkProgram) +#endif // #if defined(CL_VERSION_1_2) +#define __CREATE_KERNELS_IN_PROGRAM_ERR __ERR_STR(clCreateKernelsInProgram) + +#define __CREATE_COMMAND_QUEUE_ERR __ERR_STR(clCreateCommandQueue) +#define __SET_COMMAND_QUEUE_PROPERTY_ERR __ERR_STR(clSetCommandQueueProperty) +#define __ENQUEUE_READ_BUFFER_ERR __ERR_STR(clEnqueueReadBuffer) +#define __ENQUEUE_READ_BUFFER_RECT_ERR __ERR_STR(clEnqueueReadBufferRect) +#define __ENQUEUE_WRITE_BUFFER_ERR __ERR_STR(clEnqueueWriteBuffer) +#define __ENQUEUE_WRITE_BUFFER_RECT_ERR __ERR_STR(clEnqueueWriteBufferRect) +#define __ENQEUE_COPY_BUFFER_ERR __ERR_STR(clEnqueueCopyBuffer) +#define __ENQEUE_COPY_BUFFER_RECT_ERR __ERR_STR(clEnqueueCopyBufferRect) +#define __ENQUEUE_FILL_BUFFER_ERR __ERR_STR(clEnqueueFillBuffer) +#define __ENQUEUE_READ_IMAGE_ERR __ERR_STR(clEnqueueReadImage) +#define __ENQUEUE_WRITE_IMAGE_ERR __ERR_STR(clEnqueueWriteImage) +#define __ENQUEUE_COPY_IMAGE_ERR __ERR_STR(clEnqueueCopyImage) +#define __ENQUEUE_FILL_IMAGE_ERR __ERR_STR(clEnqueueFillImage) +#define __ENQUEUE_COPY_IMAGE_TO_BUFFER_ERR __ERR_STR(clEnqueueCopyImageToBuffer) +#define __ENQUEUE_COPY_BUFFER_TO_IMAGE_ERR __ERR_STR(clEnqueueCopyBufferToImage) +#define __ENQUEUE_MAP_BUFFER_ERR __ERR_STR(clEnqueueMapBuffer) +#define __ENQUEUE_MAP_IMAGE_ERR __ERR_STR(clEnqueueMapImage) +#define __ENQUEUE_UNMAP_MEM_OBJECT_ERR __ERR_STR(clEnqueueUnMapMemObject) +#define __ENQUEUE_NDRANGE_KERNEL_ERR __ERR_STR(clEnqueueNDRangeKernel) +#define __ENQUEUE_TASK_ERR __ERR_STR(clEnqueueTask) +#define __ENQUEUE_NATIVE_KERNEL __ERR_STR(clEnqueueNativeKernel) +#if defined(CL_VERSION_1_2) +#define __ENQUEUE_MIGRATE_MEM_OBJECTS_ERR __ERR_STR(clEnqueueMigrateMemObjects) +#endif // #if defined(CL_VERSION_1_2) + +#define __ENQUEUE_ACQUIRE_GL_ERR __ERR_STR(clEnqueueAcquireGLObjects) +#define __ENQUEUE_RELEASE_GL_ERR __ERR_STR(clEnqueueReleaseGLObjects) + + +#define __RETAIN_ERR __ERR_STR(Retain Object) +#define __RELEASE_ERR __ERR_STR(Release Object) +#define __FLUSH_ERR __ERR_STR(clFlush) +#define __FINISH_ERR __ERR_STR(clFinish) +#define __VECTOR_CAPACITY_ERR __ERR_STR(Vector capacity error) + +/** + * CL 1.2 version that uses device fission. + */ +#if defined(CL_VERSION_1_2) +#define __CREATE_SUB_DEVICES __ERR_STR(clCreateSubDevices) +#else +#define __CREATE_SUB_DEVICES __ERR_STR(clCreateSubDevicesEXT) +#endif // #if defined(CL_VERSION_1_2) + +/** + * Deprecated APIs for 1.2 + */ +#if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) || (defined(CL_VERSION_1_1) && !defined(CL_VERSION_1_2)) +#define __ENQUEUE_MARKER_ERR __ERR_STR(clEnqueueMarker) +#define __ENQUEUE_WAIT_FOR_EVENTS_ERR __ERR_STR(clEnqueueWaitForEvents) +#define __ENQUEUE_BARRIER_ERR __ERR_STR(clEnqueueBarrier) +#define __UNLOAD_COMPILER_ERR __ERR_STR(clUnloadCompiler) +#define __CREATE_GL_TEXTURE_2D_ERR __ERR_STR(clCreateFromGLTexture2D) +#define __CREATE_GL_TEXTURE_3D_ERR __ERR_STR(clCreateFromGLTexture3D) +#define __CREATE_IMAGE2D_ERR __ERR_STR(clCreateImage2D) +#define __CREATE_IMAGE3D_ERR __ERR_STR(clCreateImage3D) +#endif // #if defined(CL_VERSION_1_1) + +#endif // __CL_USER_OVERRIDE_ERROR_STRINGS +//! \endcond + +/** + * CL 1.2 marker and barrier commands + */ +#if defined(CL_VERSION_1_2) +#define __ENQUEUE_MARKER_WAIT_LIST_ERR __ERR_STR(clEnqueueMarkerWithWaitList) +#define __ENQUEUE_BARRIER_WAIT_LIST_ERR __ERR_STR(clEnqueueBarrierWithWaitList) +#endif // #if defined(CL_VERSION_1_2) + +#if !defined(__USE_DEV_STRING) && !defined(__NO_STD_STRING) +typedef std::string STRING_CLASS; +#elif !defined(__USE_DEV_STRING) + +/*! \class string + * \brief Simple string class, that provides a limited subset of std::string + * functionality but avoids many of the issues that come with that class. + + * \note Deprecated. Please use std::string as default or + * re-define the string class to match the std::string + * interface by defining STRING_CLASS + */ +class CL_EXT_PREFIX__VERSION_1_1_DEPRECATED string CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED +{ +private: + ::size_t size_; + char * str_; +public: + //! \brief Constructs an empty string, allocating no memory. + string(void) : size_(0), str_(NULL) + { + } + + /*! \brief Constructs a string populated from an arbitrary value of + * specified size. + * + * An extra '\0' is added, in case none was contained in str. + * + * \param str the initial value of the string instance. Note that '\0' + * characters receive no special treatment. If NULL, + * the string is left empty, with a size of 0. + * + * \param size the number of characters to copy from str. + */ + string(const char * str, ::size_t size) : + size_(size), + str_(NULL) + { + if( size > 0 ) { + str_ = new char[size_+1]; + if (str_ != NULL) { + memcpy(str_, str, size_ * sizeof(char)); + str_[size_] = '\0'; + } + else { + size_ = 0; + } + } + } + + /*! \brief Constructs a string populated from a null-terminated value. + * + * \param str the null-terminated initial value of the string instance. + * If NULL, the string is left empty, with a size of 0. + */ + string(const char * str) : + size_(0), + str_(NULL) + { + if( str ) { + size_= ::strlen(str); + } + if( size_ > 0 ) { + str_ = new char[size_ + 1]; + if (str_ != NULL) { + memcpy(str_, str, (size_ + 1) * sizeof(char)); + } + } + } + + void resize( ::size_t n ) + { + if( size_ == n ) { + return; + } + if (n == 0) { + if( str_ ) { + delete [] str_; + } + str_ = NULL; + size_ = 0; + } + else { + char *newString = new char[n + 1]; + ::size_t copySize = n; + if( size_ < n ) { + copySize = size_; + } + size_ = n; + + if(str_) { + memcpy(newString, str_, (copySize + 1) * sizeof(char)); + } + if( copySize < size_ ) { + memset(newString + copySize, 0, size_ - copySize); + } + newString[size_] = '\0'; + + delete [] str_; + str_ = newString; + } + } + + const char& operator[] ( ::size_t pos ) const + { + return str_[pos]; + } + + char& operator[] ( ::size_t pos ) + { + return str_[pos]; + } + + /*! \brief Copies the value of another string to this one. + * + * \param rhs the string to copy. + * + * \returns a reference to the modified instance. + */ + string& operator=(const string& rhs) + { + if (this == &rhs) { + return *this; + } + + if( str_ != NULL ) { + delete [] str_; + str_ = NULL; + size_ = 0; + } + + if (rhs.size_ == 0 || rhs.str_ == NULL) { + str_ = NULL; + size_ = 0; + } + else { + str_ = new char[rhs.size_ + 1]; + size_ = rhs.size_; + + if (str_ != NULL) { + memcpy(str_, rhs.str_, (size_ + 1) * sizeof(char)); + } + else { + size_ = 0; + } + } + + return *this; + } + + /*! \brief Constructs a string by copying the value of another instance. + * + * \param rhs the string to copy. + */ + string(const string& rhs) : + size_(0), + str_(NULL) + { + *this = rhs; + } + + //! \brief Destructor - frees memory used to hold the current value. + ~string() + { + delete[] str_; + str_ = NULL; + } + + //! \brief Queries the length of the string, excluding any added '\0's. + ::size_t size(void) const { return size_; } + + //! \brief Queries the length of the string, excluding any added '\0's. + ::size_t length(void) const { return size(); } + + /*! \brief Returns a pointer to the private copy held by this instance, + * or "" if empty/unset. + */ + const char * c_str(void) const { return (str_) ? str_ : "";} +}; +typedef cl::string STRING_CLASS; +#endif // #elif !defined(__USE_DEV_STRING) + +#if !defined(__USE_DEV_VECTOR) && !defined(__NO_STD_VECTOR) +#define VECTOR_CLASS std::vector +#elif !defined(__USE_DEV_VECTOR) +#define VECTOR_CLASS cl::vector + +#if !defined(__MAX_DEFAULT_VECTOR_SIZE) +#define __MAX_DEFAULT_VECTOR_SIZE 10 +#endif + +/*! \class vector + * \brief Fixed sized vector implementation that mirroring + * + * \note Deprecated. Please use std::vector as default or + * re-define the vector class to match the std::vector + * interface by defining VECTOR_CLASS + + * \note Not recommended for use with custom objects as + * current implementation will construct N elements + * + * std::vector functionality. + * \brief Fixed sized vector compatible with std::vector. + * + * \note + * This differs from std::vector<> not just in memory allocation, + * but also in terms of when members are constructed, destroyed, + * and assigned instead of being copy constructed. + * + * \param T type of element contained in the vector. + * + * \param N maximum size of the vector. + */ +template +class CL_EXT_PREFIX__VERSION_1_1_DEPRECATED vector +{ +private: + T data_[N]; + unsigned int size_; + +public: + //! \brief Constructs an empty vector with no memory allocated. + vector() : + size_(static_cast(0)) + {} + + //! \brief Deallocates the vector's memory and destroys all of its elements. + ~vector() + { + clear(); + } + + //! \brief Returns the number of elements currently contained. + unsigned int size(void) const + { + return size_; + } + + /*! \brief Empties the vector of all elements. + * \note + * This does not deallocate memory but will invoke destructors + * on contained elements. + */ + void clear() + { + while(!empty()) { + pop_back(); + } + } + + /*! \brief Appends an element after the last valid element. + * Calling this on a vector that has reached capacity will throw an + * exception if exceptions are enabled. + */ + void push_back (const T& x) + { + if (size() < N) { + new (&data_[size_]) T(x); + size_++; + } else { + detail::errHandler(CL_MEM_OBJECT_ALLOCATION_FAILURE, __VECTOR_CAPACITY_ERR); + } + } + + /*! \brief Removes the last valid element from the vector. + * Calling this on an empty vector will throw an exception + * if exceptions are enabled. + */ + void pop_back(void) + { + if (size_ != 0) { + --size_; + data_[size_].~T(); + } else { + detail::errHandler(CL_MEM_OBJECT_ALLOCATION_FAILURE, __VECTOR_CAPACITY_ERR); + } + } + + /*! \brief Constructs with a value copied from another. + * + * \param vec the vector to copy. + */ + vector(const vector& vec) : + size_(vec.size_) + { + if (size_ != 0) { + assign(vec.begin(), vec.end()); + } + } + + /*! \brief Constructs with a specified number of initial elements. + * + * \param size number of initial elements. + * + * \param val value of initial elements. + */ + vector(unsigned int size, const T& val = T()) : + size_(0) + { + for (unsigned int i = 0; i < size; i++) { + push_back(val); + } + } + + /*! \brief Overwrites the current content with that copied from another + * instance. + * + * \param rhs vector to copy. + * + * \returns a reference to this. + */ + vector& operator=(const vector& rhs) + { + if (this == &rhs) { + return *this; + } + + if (rhs.size_ != 0) { + assign(rhs.begin(), rhs.end()); + } else { + clear(); + } + + return *this; + } + + /*! \brief Tests equality against another instance. + * + * \param vec the vector against which to compare. + */ + bool operator==(vector &vec) + { + if (size() != vec.size()) { + return false; + } + + for( unsigned int i = 0; i < size(); ++i ) { + if( operator[](i) != vec[i] ) { + return false; + } + } + return true; + } + + //! \brief Conversion operator to T*. + operator T* () { return data_; } + + //! \brief Conversion operator to const T*. + operator const T* () const { return data_; } + + //! \brief Tests whether this instance has any elements. + bool empty (void) const + { + return size_==0; + } + + //! \brief Returns the maximum number of elements this instance can hold. + unsigned int max_size (void) const + { + return N; + } + + //! \brief Returns the maximum number of elements this instance can hold. + unsigned int capacity () const + { + return N; + } + + //! \brief Resizes the vector to the given size + void resize(unsigned int newSize, T fill = T()) + { + if (newSize > N) + { + detail::errHandler(CL_MEM_OBJECT_ALLOCATION_FAILURE, __VECTOR_CAPACITY_ERR); + } + else + { + while (size_ < newSize) + { + new (&data_[size_]) T(fill); + size_++; + } + while (size_ > newSize) + { + --size_; + data_[size_].~T(); + } + } + } + + /*! \brief Returns a reference to a given element. + * + * \param index which element to access. * + * \note + * The caller is responsible for ensuring index is >= 0 and < size(). + */ + T& operator[](int index) + { + return data_[index]; + } + + /*! \brief Returns a const reference to a given element. + * + * \param index which element to access. + * + * \note + * The caller is responsible for ensuring index is >= 0 and < size(). + */ + const T& operator[](int index) const + { + return data_[index]; + } + + /*! \brief Assigns elements of the vector based on a source iterator range. + * + * \param start Beginning iterator of source range + * \param end Enditerator of source range + * + * \note + * Will throw an exception if exceptions are enabled and size exceeded. + */ + template + void assign(I start, I end) + { + clear(); + while(start != end) { + push_back(*start); + start++; + } + } + + /*! \class iterator + * \brief Const iterator class for vectors + */ + class iterator + { + private: + const vector *vec_; + int index_; + + /** + * Internal iterator constructor to capture reference + * to the vector it iterates over rather than taking + * the vector by copy. + */ + iterator (const vector &vec, int index) : + vec_(&vec) + { + if( !vec.empty() ) { + index_ = index; + } else { + index_ = -1; + } + } + + public: + iterator(void) : + index_(-1), + vec_(NULL) + { + } + + iterator(const iterator& rhs) : + vec_(rhs.vec_), + index_(rhs.index_) + { + } + + ~iterator(void) {} + + static iterator begin(const cl::vector &vec) + { + iterator i(vec, 0); + + return i; + } + + static iterator end(const cl::vector &vec) + { + iterator i(vec, vec.size()); + + return i; + } + + bool operator==(iterator i) + { + return ((vec_ == i.vec_) && + (index_ == i.index_)); + } + + bool operator!=(iterator i) + { + return (!(*this==i)); + } + + iterator& operator++() + { + ++index_; + return *this; + } + + iterator operator++(int) + { + iterator retVal(*this); + ++index_; + return retVal; + } + + iterator& operator--() + { + --index_; + return *this; + } + + iterator operator--(int) + { + iterator retVal(*this); + --index_; + return retVal; + } + + const T& operator *() const + { + return (*vec_)[index_]; + } + }; + + iterator begin(void) + { + return iterator::begin(*this); + } + + iterator begin(void) const + { + return iterator::begin(*this); + } + + iterator end(void) + { + return iterator::end(*this); + } + + iterator end(void) const + { + return iterator::end(*this); + } + + T& front(void) + { + return data_[0]; + } + + T& back(void) + { + return data_[size_]; + } + + const T& front(void) const + { + return data_[0]; + } + + const T& back(void) const + { + return data_[size_-1]; + } +} CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; +#endif // #if !defined(__USE_DEV_VECTOR) && !defined(__NO_STD_VECTOR) + + + + + +namespace detail { +#define __DEFAULT_NOT_INITIALIZED 1 +#define __DEFAULT_BEING_INITIALIZED 2 +#define __DEFAULT_INITIALIZED 4 + + /* + * Compare and exchange primitives are needed for handling of defaults + */ + +#ifdef CL_HPP_CPP11_ATOMICS_SUPPORTED + inline int compare_exchange(std::atomic * dest, int exchange, int comparand) +#else // !CL_HPP_CPP11_ATOMICS_SUPPORTED + inline int compare_exchange(volatile int * dest, int exchange, int comparand) +#endif // !CL_HPP_CPP11_ATOMICS_SUPPORTED + { +#ifdef CL_HPP_CPP11_ATOMICS_SUPPORTED + std::atomic_compare_exchange_strong(dest, &comparand, exchange); + return comparand; +#elif _MSC_VER + return (int)(_InterlockedCompareExchange( + (volatile long*)dest, + (long)exchange, + (long)comparand)); +#else // !_MSC_VER && !CL_HPP_CPP11_ATOMICS_SUPPORTED + return (__sync_val_compare_and_swap( + dest, + comparand, + exchange)); +#endif // !CL_HPP_CPP11_ATOMICS_SUPPORTED + } + + inline void fence() { +#ifdef CL_HPP_CPP11_ATOMICS_SUPPORTED + std::atomic_thread_fence(std::memory_order_seq_cst); +#elif _MSC_VER // !CL_HPP_CPP11_ATOMICS_SUPPORTED + _ReadWriteBarrier(); +#else // !_MSC_VER && !CL_HPP_CPP11_ATOMICS_SUPPORTED + __sync_synchronize(); +#endif // !CL_HPP_CPP11_ATOMICS_SUPPORTED + } +} // namespace detail + + +/*! \brief class used to interface between C++ and + * OpenCL C calls that require arrays of size_t values, whose + * size is known statically. + */ +template +class size_t +{ +private: + ::size_t data_[N]; + +public: + //! \brief Initialize size_t to all 0s + size_t() + { + for( int i = 0; i < N; ++i ) { + data_[i] = 0; + } + } + + ::size_t& operator[](int index) + { + return data_[index]; + } + + const ::size_t& operator[](int index) const + { + return data_[index]; + } + + //! \brief Conversion operator to T*. + operator ::size_t* () { return data_; } + + //! \brief Conversion operator to const T*. + operator const ::size_t* () const { return data_; } +}; + +namespace detail { + +// Generic getInfoHelper. The final parameter is used to guide overload +// resolution: the actual parameter passed is an int, which makes this +// a worse conversion sequence than a specialization that declares the +// parameter as an int. +template +inline cl_int getInfoHelper(Functor f, cl_uint name, T* param, long) +{ + return f(name, sizeof(T), param, NULL); +} + +// Specialized getInfoHelper for VECTOR_CLASS params +template +inline cl_int getInfoHelper(Func f, cl_uint name, VECTOR_CLASS* param, long) +{ + ::size_t required; + cl_int err = f(name, 0, NULL, &required); + if (err != CL_SUCCESS) { + return err; + } + + T* value = (T*) alloca(required); + err = f(name, required, value, NULL); + if (err != CL_SUCCESS) { + return err; + } + + param->assign(&value[0], &value[required/sizeof(T)]); + return CL_SUCCESS; +} + +/* Specialization for reference-counted types. This depends on the + * existence of Wrapper::cl_type, and none of the other types having the + * cl_type member. Note that simplify specifying the parameter as Wrapper + * does not work, because when using a derived type (e.g. Context) the generic + * template will provide a better match. + */ +template +inline cl_int getInfoHelper(Func f, cl_uint name, VECTOR_CLASS* param, int, typename T::cl_type = 0) +{ + ::size_t required; + cl_int err = f(name, 0, NULL, &required); + if (err != CL_SUCCESS) { + return err; + } + + typename T::cl_type * value = (typename T::cl_type *) alloca(required); + err = f(name, required, value, NULL); + if (err != CL_SUCCESS) { + return err; + } + + ::size_t elements = required / sizeof(typename T::cl_type); + param->assign(&value[0], &value[elements]); + for (::size_t i = 0; i < elements; i++) + { + if (value[i] != NULL) + { + err = (*param)[i].retain(); + if (err != CL_SUCCESS) { + return err; + } + } + } + return CL_SUCCESS; +} + +// Specialized for getInfo +template +inline cl_int getInfoHelper(Func f, cl_uint name, VECTOR_CLASS* param, int) +{ + cl_int err = f(name, param->size() * sizeof(char *), &(*param)[0], NULL); + + if (err != CL_SUCCESS) { + return err; + } + + return CL_SUCCESS; +} + +// Specialized GetInfoHelper for STRING_CLASS params +template +inline cl_int getInfoHelper(Func f, cl_uint name, STRING_CLASS* param, long) +{ + ::size_t required; + cl_int err = f(name, 0, NULL, &required); + if (err != CL_SUCCESS) { + return err; + } + + // std::string has a constant data member + // a char vector does not + VECTOR_CLASS value(required); + err = f(name, required, value.data(), NULL); + if (err != CL_SUCCESS) { + return err; + } + if (param) { + param->assign(value.begin(), value.end()); + } + return CL_SUCCESS; +} + +// Specialized GetInfoHelper for cl::size_t params +template +inline cl_int getInfoHelper(Func f, cl_uint name, size_t* param, long) +{ + ::size_t required; + cl_int err = f(name, 0, NULL, &required); + if (err != CL_SUCCESS) { + return err; + } + + ::size_t* value = (::size_t*) alloca(required); + err = f(name, required, value, NULL); + if (err != CL_SUCCESS) { + return err; + } + + for(int i = 0; i < N; ++i) { + (*param)[i] = value[i]; + } + + return CL_SUCCESS; +} + +template struct ReferenceHandler; + +/* Specialization for reference-counted types. This depends on the + * existence of Wrapper::cl_type, and none of the other types having the + * cl_type member. Note that simplify specifying the parameter as Wrapper + * does not work, because when using a derived type (e.g. Context) the generic + * template will provide a better match. + */ +template +inline cl_int getInfoHelper(Func f, cl_uint name, T* param, int, typename T::cl_type = 0) +{ + typename T::cl_type value; + cl_int err = f(name, sizeof(value), &value, NULL); + if (err != CL_SUCCESS) { + return err; + } + *param = value; + if (value != NULL) + { + err = param->retain(); + if (err != CL_SUCCESS) { + return err; + } + } + return CL_SUCCESS; +} + +#define __PARAM_NAME_INFO_1_0(F) \ + F(cl_platform_info, CL_PLATFORM_PROFILE, STRING_CLASS) \ + F(cl_platform_info, CL_PLATFORM_VERSION, STRING_CLASS) \ + F(cl_platform_info, CL_PLATFORM_NAME, STRING_CLASS) \ + F(cl_platform_info, CL_PLATFORM_VENDOR, STRING_CLASS) \ + F(cl_platform_info, CL_PLATFORM_EXTENSIONS, STRING_CLASS) \ + \ + F(cl_device_info, CL_DEVICE_TYPE, cl_device_type) \ + F(cl_device_info, CL_DEVICE_VENDOR_ID, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_COMPUTE_UNITS, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_WORK_GROUP_SIZE, ::size_t) \ + F(cl_device_info, CL_DEVICE_MAX_WORK_ITEM_SIZES, VECTOR_CLASS< ::size_t>) \ + F(cl_device_info, CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR, cl_uint) \ + F(cl_device_info, CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT, cl_uint) \ + F(cl_device_info, CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT, cl_uint) \ + F(cl_device_info, CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG, cl_uint) \ + F(cl_device_info, CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT, cl_uint) \ + F(cl_device_info, CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_CLOCK_FREQUENCY, cl_uint) \ + F(cl_device_info, CL_DEVICE_ADDRESS_BITS, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_READ_IMAGE_ARGS, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_WRITE_IMAGE_ARGS, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_MEM_ALLOC_SIZE, cl_ulong) \ + F(cl_device_info, CL_DEVICE_IMAGE2D_MAX_WIDTH, ::size_t) \ + F(cl_device_info, CL_DEVICE_IMAGE2D_MAX_HEIGHT, ::size_t) \ + F(cl_device_info, CL_DEVICE_IMAGE3D_MAX_WIDTH, ::size_t) \ + F(cl_device_info, CL_DEVICE_IMAGE3D_MAX_HEIGHT, ::size_t) \ + F(cl_device_info, CL_DEVICE_IMAGE3D_MAX_DEPTH, ::size_t) \ + F(cl_device_info, CL_DEVICE_IMAGE_SUPPORT, cl_bool) \ + F(cl_device_info, CL_DEVICE_MAX_PARAMETER_SIZE, ::size_t) \ + F(cl_device_info, CL_DEVICE_MAX_SAMPLERS, cl_uint) \ + F(cl_device_info, CL_DEVICE_MEM_BASE_ADDR_ALIGN, cl_uint) \ + F(cl_device_info, CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE, cl_uint) \ + F(cl_device_info, CL_DEVICE_SINGLE_FP_CONFIG, cl_device_fp_config) \ + F(cl_device_info, CL_DEVICE_GLOBAL_MEM_CACHE_TYPE, cl_device_mem_cache_type) \ + F(cl_device_info, CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE, cl_uint)\ + F(cl_device_info, CL_DEVICE_GLOBAL_MEM_CACHE_SIZE, cl_ulong) \ + F(cl_device_info, CL_DEVICE_GLOBAL_MEM_SIZE, cl_ulong) \ + F(cl_device_info, CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE, cl_ulong) \ + F(cl_device_info, CL_DEVICE_MAX_CONSTANT_ARGS, cl_uint) \ + F(cl_device_info, CL_DEVICE_LOCAL_MEM_TYPE, cl_device_local_mem_type) \ + F(cl_device_info, CL_DEVICE_LOCAL_MEM_SIZE, cl_ulong) \ + F(cl_device_info, CL_DEVICE_ERROR_CORRECTION_SUPPORT, cl_bool) \ + F(cl_device_info, CL_DEVICE_PROFILING_TIMER_RESOLUTION, ::size_t) \ + F(cl_device_info, CL_DEVICE_ENDIAN_LITTLE, cl_bool) \ + F(cl_device_info, CL_DEVICE_AVAILABLE, cl_bool) \ + F(cl_device_info, CL_DEVICE_COMPILER_AVAILABLE, cl_bool) \ + F(cl_device_info, CL_DEVICE_EXECUTION_CAPABILITIES, cl_device_exec_capabilities) \ + F(cl_device_info, CL_DEVICE_QUEUE_PROPERTIES, cl_command_queue_properties) \ + F(cl_device_info, CL_DEVICE_PLATFORM, cl_platform_id) \ + F(cl_device_info, CL_DEVICE_NAME, STRING_CLASS) \ + F(cl_device_info, CL_DEVICE_VENDOR, STRING_CLASS) \ + F(cl_device_info, CL_DRIVER_VERSION, STRING_CLASS) \ + F(cl_device_info, CL_DEVICE_PROFILE, STRING_CLASS) \ + F(cl_device_info, CL_DEVICE_VERSION, STRING_CLASS) \ + F(cl_device_info, CL_DEVICE_EXTENSIONS, STRING_CLASS) \ + \ + F(cl_context_info, CL_CONTEXT_REFERENCE_COUNT, cl_uint) \ + F(cl_context_info, CL_CONTEXT_DEVICES, VECTOR_CLASS) \ + F(cl_context_info, CL_CONTEXT_PROPERTIES, VECTOR_CLASS) \ + \ + F(cl_event_info, CL_EVENT_COMMAND_QUEUE, cl::CommandQueue) \ + F(cl_event_info, CL_EVENT_COMMAND_TYPE, cl_command_type) \ + F(cl_event_info, CL_EVENT_REFERENCE_COUNT, cl_uint) \ + F(cl_event_info, CL_EVENT_COMMAND_EXECUTION_STATUS, cl_int) \ + \ + F(cl_profiling_info, CL_PROFILING_COMMAND_QUEUED, cl_ulong) \ + F(cl_profiling_info, CL_PROFILING_COMMAND_SUBMIT, cl_ulong) \ + F(cl_profiling_info, CL_PROFILING_COMMAND_START, cl_ulong) \ + F(cl_profiling_info, CL_PROFILING_COMMAND_END, cl_ulong) \ + \ + F(cl_mem_info, CL_MEM_TYPE, cl_mem_object_type) \ + F(cl_mem_info, CL_MEM_FLAGS, cl_mem_flags) \ + F(cl_mem_info, CL_MEM_SIZE, ::size_t) \ + F(cl_mem_info, CL_MEM_HOST_PTR, void*) \ + F(cl_mem_info, CL_MEM_MAP_COUNT, cl_uint) \ + F(cl_mem_info, CL_MEM_REFERENCE_COUNT, cl_uint) \ + F(cl_mem_info, CL_MEM_CONTEXT, cl::Context) \ + \ + F(cl_image_info, CL_IMAGE_FORMAT, cl_image_format) \ + F(cl_image_info, CL_IMAGE_ELEMENT_SIZE, ::size_t) \ + F(cl_image_info, CL_IMAGE_ROW_PITCH, ::size_t) \ + F(cl_image_info, CL_IMAGE_SLICE_PITCH, ::size_t) \ + F(cl_image_info, CL_IMAGE_WIDTH, ::size_t) \ + F(cl_image_info, CL_IMAGE_HEIGHT, ::size_t) \ + F(cl_image_info, CL_IMAGE_DEPTH, ::size_t) \ + \ + F(cl_sampler_info, CL_SAMPLER_REFERENCE_COUNT, cl_uint) \ + F(cl_sampler_info, CL_SAMPLER_CONTEXT, cl::Context) \ + F(cl_sampler_info, CL_SAMPLER_NORMALIZED_COORDS, cl_addressing_mode) \ + F(cl_sampler_info, CL_SAMPLER_ADDRESSING_MODE, cl_filter_mode) \ + F(cl_sampler_info, CL_SAMPLER_FILTER_MODE, cl_bool) \ + \ + F(cl_program_info, CL_PROGRAM_REFERENCE_COUNT, cl_uint) \ + F(cl_program_info, CL_PROGRAM_CONTEXT, cl::Context) \ + F(cl_program_info, CL_PROGRAM_NUM_DEVICES, cl_uint) \ + F(cl_program_info, CL_PROGRAM_DEVICES, VECTOR_CLASS) \ + F(cl_program_info, CL_PROGRAM_SOURCE, STRING_CLASS) \ + F(cl_program_info, CL_PROGRAM_BINARY_SIZES, VECTOR_CLASS< ::size_t>) \ + F(cl_program_info, CL_PROGRAM_BINARIES, VECTOR_CLASS) \ + \ + F(cl_program_build_info, CL_PROGRAM_BUILD_STATUS, cl_build_status) \ + F(cl_program_build_info, CL_PROGRAM_BUILD_OPTIONS, STRING_CLASS) \ + F(cl_program_build_info, CL_PROGRAM_BUILD_LOG, STRING_CLASS) \ + \ + F(cl_kernel_info, CL_KERNEL_FUNCTION_NAME, STRING_CLASS) \ + F(cl_kernel_info, CL_KERNEL_NUM_ARGS, cl_uint) \ + F(cl_kernel_info, CL_KERNEL_REFERENCE_COUNT, cl_uint) \ + F(cl_kernel_info, CL_KERNEL_CONTEXT, cl::Context) \ + F(cl_kernel_info, CL_KERNEL_PROGRAM, cl::Program) \ + \ + F(cl_kernel_work_group_info, CL_KERNEL_WORK_GROUP_SIZE, ::size_t) \ + F(cl_kernel_work_group_info, CL_KERNEL_COMPILE_WORK_GROUP_SIZE, cl::size_t<3>) \ + F(cl_kernel_work_group_info, CL_KERNEL_LOCAL_MEM_SIZE, cl_ulong) \ + \ + F(cl_command_queue_info, CL_QUEUE_CONTEXT, cl::Context) \ + F(cl_command_queue_info, CL_QUEUE_DEVICE, cl::Device) \ + F(cl_command_queue_info, CL_QUEUE_REFERENCE_COUNT, cl_uint) \ + F(cl_command_queue_info, CL_QUEUE_PROPERTIES, cl_command_queue_properties) + +#if defined(CL_VERSION_1_1) +#define __PARAM_NAME_INFO_1_1(F) \ + F(cl_context_info, CL_CONTEXT_NUM_DEVICES, cl_uint)\ + F(cl_device_info, CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF, cl_uint) \ + F(cl_device_info, CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR, cl_uint) \ + F(cl_device_info, CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT, cl_uint) \ + F(cl_device_info, CL_DEVICE_NATIVE_VECTOR_WIDTH_INT, cl_uint) \ + F(cl_device_info, CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG, cl_uint) \ + F(cl_device_info, CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT, cl_uint) \ + F(cl_device_info, CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE, cl_uint) \ + F(cl_device_info, CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF, cl_uint) \ + F(cl_device_info, CL_DEVICE_DOUBLE_FP_CONFIG, cl_device_fp_config) \ + F(cl_device_info, CL_DEVICE_HALF_FP_CONFIG, cl_device_fp_config) \ + F(cl_device_info, CL_DEVICE_HOST_UNIFIED_MEMORY, cl_bool) \ + F(cl_device_info, CL_DEVICE_OPENCL_C_VERSION, STRING_CLASS) \ + \ + F(cl_mem_info, CL_MEM_ASSOCIATED_MEMOBJECT, cl::Memory) \ + F(cl_mem_info, CL_MEM_OFFSET, ::size_t) \ + \ + F(cl_kernel_work_group_info, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, ::size_t) \ + F(cl_kernel_work_group_info, CL_KERNEL_PRIVATE_MEM_SIZE, cl_ulong) \ + \ + F(cl_event_info, CL_EVENT_CONTEXT, cl::Context) +#endif // CL_VERSION_1_1 + + +#if defined(CL_VERSION_1_2) +#define __PARAM_NAME_INFO_1_2(F) \ + F(cl_image_info, CL_IMAGE_BUFFER, cl::Buffer) \ + \ + F(cl_program_info, CL_PROGRAM_NUM_KERNELS, ::size_t) \ + F(cl_program_info, CL_PROGRAM_KERNEL_NAMES, STRING_CLASS) \ + \ + F(cl_program_build_info, CL_PROGRAM_BINARY_TYPE, cl_program_binary_type) \ + \ + F(cl_kernel_info, CL_KERNEL_ATTRIBUTES, STRING_CLASS) \ + \ + F(cl_kernel_arg_info, CL_KERNEL_ARG_ADDRESS_QUALIFIER, cl_kernel_arg_address_qualifier) \ + F(cl_kernel_arg_info, CL_KERNEL_ARG_ACCESS_QUALIFIER, cl_kernel_arg_access_qualifier) \ + F(cl_kernel_arg_info, CL_KERNEL_ARG_TYPE_NAME, STRING_CLASS) \ + F(cl_kernel_arg_info, CL_KERNEL_ARG_NAME, STRING_CLASS) \ + \ + F(cl_device_info, CL_DEVICE_PARENT_DEVICE, cl_device_id) \ + F(cl_device_info, CL_DEVICE_PARTITION_PROPERTIES, VECTOR_CLASS) \ + F(cl_device_info, CL_DEVICE_PARTITION_TYPE, VECTOR_CLASS) \ + F(cl_device_info, CL_DEVICE_REFERENCE_COUNT, cl_uint) \ + F(cl_device_info, CL_DEVICE_PREFERRED_INTEROP_USER_SYNC, ::size_t) \ + F(cl_device_info, CL_DEVICE_PARTITION_AFFINITY_DOMAIN, cl_device_affinity_domain) \ + F(cl_device_info, CL_DEVICE_BUILT_IN_KERNELS, STRING_CLASS) +#endif // #if defined(CL_VERSION_1_2) + +#if defined(USE_CL_DEVICE_FISSION) +#define __PARAM_NAME_DEVICE_FISSION(F) \ + F(cl_device_info, CL_DEVICE_PARENT_DEVICE_EXT, cl_device_id) \ + F(cl_device_info, CL_DEVICE_PARTITION_TYPES_EXT, VECTOR_CLASS) \ + F(cl_device_info, CL_DEVICE_AFFINITY_DOMAINS_EXT, VECTOR_CLASS) \ + F(cl_device_info, CL_DEVICE_REFERENCE_COUNT_EXT , cl_uint) \ + F(cl_device_info, CL_DEVICE_PARTITION_STYLE_EXT, VECTOR_CLASS) +#endif // USE_CL_DEVICE_FISSION + +template +struct param_traits {}; + +#define __CL_DECLARE_PARAM_TRAITS(token, param_name, T) \ +struct token; \ +template<> \ +struct param_traits \ +{ \ + enum { value = param_name }; \ + typedef T param_type; \ +}; + +__PARAM_NAME_INFO_1_0(__CL_DECLARE_PARAM_TRAITS) +#if defined(CL_VERSION_1_1) +__PARAM_NAME_INFO_1_1(__CL_DECLARE_PARAM_TRAITS) +#endif // CL_VERSION_1_1 +#if defined(CL_VERSION_1_2) +__PARAM_NAME_INFO_1_2(__CL_DECLARE_PARAM_TRAITS) +#endif // CL_VERSION_1_1 + +#if defined(USE_CL_DEVICE_FISSION) +__PARAM_NAME_DEVICE_FISSION(__CL_DECLARE_PARAM_TRAITS); +#endif // USE_CL_DEVICE_FISSION + +#ifdef CL_PLATFORM_ICD_SUFFIX_KHR +__CL_DECLARE_PARAM_TRAITS(cl_platform_info, CL_PLATFORM_ICD_SUFFIX_KHR, STRING_CLASS) +#endif + +#ifdef CL_DEVICE_PROFILING_TIMER_OFFSET_AMD +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_PROFILING_TIMER_OFFSET_AMD, cl_ulong) +#endif + +#ifdef CL_DEVICE_GLOBAL_FREE_MEMORY_AMD +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_GLOBAL_FREE_MEMORY_AMD, VECTOR_CLASS< ::size_t>) +#endif +#ifdef CL_DEVICE_SIMD_PER_COMPUTE_UNIT_AMD +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_SIMD_PER_COMPUTE_UNIT_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_SIMD_WIDTH_AMD +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_SIMD_WIDTH_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_SIMD_INSTRUCTION_WIDTH_AMD +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_SIMD_INSTRUCTION_WIDTH_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_WAVEFRONT_WIDTH_AMD +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_WAVEFRONT_WIDTH_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_GLOBAL_MEM_CHANNELS_AMD +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_GLOBAL_MEM_CHANNELS_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_GLOBAL_MEM_CHANNEL_BANKS_AMD +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_GLOBAL_MEM_CHANNEL_BANKS_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_GLOBAL_MEM_CHANNEL_BANK_WIDTH_AMD +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_GLOBAL_MEM_CHANNEL_BANK_WIDTH_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_LOCAL_MEM_SIZE_PER_COMPUTE_UNIT_AMD +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_LOCAL_MEM_SIZE_PER_COMPUTE_UNIT_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_LOCAL_MEM_BANKS_AMD +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_LOCAL_MEM_BANKS_AMD, cl_uint) +#endif + +#ifdef CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV, cl_uint) +#endif +#ifdef CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV, cl_uint) +#endif +#ifdef CL_DEVICE_REGISTERS_PER_BLOCK_NV +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_REGISTERS_PER_BLOCK_NV, cl_uint) +#endif +#ifdef CL_DEVICE_WARP_SIZE_NV +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_WARP_SIZE_NV, cl_uint) +#endif +#ifdef CL_DEVICE_GPU_OVERLAP_NV +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_GPU_OVERLAP_NV, cl_bool) +#endif +#ifdef CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV, cl_bool) +#endif +#ifdef CL_DEVICE_INTEGRATED_MEMORY_NV +__CL_DECLARE_PARAM_TRAITS(cl_device_info, CL_DEVICE_INTEGRATED_MEMORY_NV, cl_bool) +#endif + +// Convenience functions + +template +inline cl_int +getInfo(Func f, cl_uint name, T* param) +{ + return getInfoHelper(f, name, param, 0); +} + +template +struct GetInfoFunctor0 +{ + Func f_; const Arg0& arg0_; + cl_int operator ()( + cl_uint param, ::size_t size, void* value, ::size_t* size_ret) + { return f_(arg0_, param, size, value, size_ret); } +}; + +template +struct GetInfoFunctor1 +{ + Func f_; const Arg0& arg0_; const Arg1& arg1_; + cl_int operator ()( + cl_uint param, ::size_t size, void* value, ::size_t* size_ret) + { return f_(arg0_, arg1_, param, size, value, size_ret); } +}; + +template +inline cl_int +getInfo(Func f, const Arg0& arg0, cl_uint name, T* param) +{ + GetInfoFunctor0 f0 = { f, arg0 }; + return getInfoHelper(f0, name, param, 0); +} + +template +inline cl_int +getInfo(Func f, const Arg0& arg0, const Arg1& arg1, cl_uint name, T* param) +{ + GetInfoFunctor1 f0 = { f, arg0, arg1 }; + return getInfoHelper(f0, name, param, 0); +} + +template +struct ReferenceHandler +{ }; + +#if defined(CL_VERSION_1_2) +/** + * OpenCL 1.2 devices do have retain/release. + */ +template <> +struct ReferenceHandler +{ + /** + * Retain the device. + * \param device A valid device created using createSubDevices + * \return + * CL_SUCCESS if the function executed successfully. + * CL_INVALID_DEVICE if device was not a valid subdevice + * CL_OUT_OF_RESOURCES + * CL_OUT_OF_HOST_MEMORY + */ + static cl_int retain(cl_device_id device) + { return ::clRetainDevice(device); } + /** + * Retain the device. + * \param device A valid device created using createSubDevices + * \return + * CL_SUCCESS if the function executed successfully. + * CL_INVALID_DEVICE if device was not a valid subdevice + * CL_OUT_OF_RESOURCES + * CL_OUT_OF_HOST_MEMORY + */ + static cl_int release(cl_device_id device) + { return ::clReleaseDevice(device); } +}; +#else // #if defined(CL_VERSION_1_2) +/** + * OpenCL 1.1 devices do not have retain/release. + */ +template <> +struct ReferenceHandler +{ + // cl_device_id does not have retain(). + static cl_int retain(cl_device_id) + { return CL_SUCCESS; } + // cl_device_id does not have release(). + static cl_int release(cl_device_id) + { return CL_SUCCESS; } +}; +#endif // #if defined(CL_VERSION_1_2) + +template <> +struct ReferenceHandler +{ + // cl_platform_id does not have retain(). + static cl_int retain(cl_platform_id) + { return CL_SUCCESS; } + // cl_platform_id does not have release(). + static cl_int release(cl_platform_id) + { return CL_SUCCESS; } +}; + +template <> +struct ReferenceHandler +{ + static cl_int retain(cl_context context) + { return ::clRetainContext(context); } + static cl_int release(cl_context context) + { return ::clReleaseContext(context); } +}; + +template <> +struct ReferenceHandler +{ + static cl_int retain(cl_command_queue queue) + { return ::clRetainCommandQueue(queue); } + static cl_int release(cl_command_queue queue) + { return ::clReleaseCommandQueue(queue); } +}; + +template <> +struct ReferenceHandler +{ + static cl_int retain(cl_mem memory) + { return ::clRetainMemObject(memory); } + static cl_int release(cl_mem memory) + { return ::clReleaseMemObject(memory); } +}; + +template <> +struct ReferenceHandler +{ + static cl_int retain(cl_sampler sampler) + { return ::clRetainSampler(sampler); } + static cl_int release(cl_sampler sampler) + { return ::clReleaseSampler(sampler); } +}; + +template <> +struct ReferenceHandler +{ + static cl_int retain(cl_program program) + { return ::clRetainProgram(program); } + static cl_int release(cl_program program) + { return ::clReleaseProgram(program); } +}; + +template <> +struct ReferenceHandler +{ + static cl_int retain(cl_kernel kernel) + { return ::clRetainKernel(kernel); } + static cl_int release(cl_kernel kernel) + { return ::clReleaseKernel(kernel); } +}; + +template <> +struct ReferenceHandler +{ + static cl_int retain(cl_event event) + { return ::clRetainEvent(event); } + static cl_int release(cl_event event) + { return ::clReleaseEvent(event); } +}; + + +// Extracts version number with major in the upper 16 bits, minor in the lower 16 +static cl_uint getVersion(const char *versionInfo) +{ + int highVersion = 0; + int lowVersion = 0; + int index = 7; + while(versionInfo[index] != '.' ) { + highVersion *= 10; + highVersion += versionInfo[index]-'0'; + ++index; + } + ++index; + while(versionInfo[index] != ' ' && versionInfo[index] != '\0') { + lowVersion *= 10; + lowVersion += versionInfo[index]-'0'; + ++index; + } + return (highVersion << 16) | lowVersion; +} + +static cl_uint getPlatformVersion(cl_platform_id platform) +{ + ::size_t size = 0; + clGetPlatformInfo(platform, CL_PLATFORM_VERSION, 0, NULL, &size); + char *versionInfo = (char *) alloca(size); + clGetPlatformInfo(platform, CL_PLATFORM_VERSION, size, &versionInfo[0], &size); + return getVersion(versionInfo); +} + +static cl_uint getDevicePlatformVersion(cl_device_id device) +{ + cl_platform_id platform; + clGetDeviceInfo(device, CL_DEVICE_PLATFORM, sizeof(platform), &platform, NULL); + return getPlatformVersion(platform); +} + +#if defined(CL_VERSION_1_2) && defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) +static cl_uint getContextPlatformVersion(cl_context context) +{ + // The platform cannot be queried directly, so we first have to grab a + // device and obtain its context + ::size_t size = 0; + clGetContextInfo(context, CL_CONTEXT_DEVICES, 0, NULL, &size); + if (size == 0) + return 0; + cl_device_id *devices = (cl_device_id *) alloca(size); + clGetContextInfo(context, CL_CONTEXT_DEVICES, size, devices, NULL); + return getDevicePlatformVersion(devices[0]); +} +#endif // #if defined(CL_VERSION_1_2) && defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + +template +class Wrapper +{ +public: + typedef T cl_type; + +protected: + cl_type object_; + +public: + Wrapper() : object_(NULL) { } + + Wrapper(const cl_type &obj) : object_(obj) { } + + ~Wrapper() + { + if (object_ != NULL) { release(); } + } + + Wrapper(const Wrapper& rhs) + { + object_ = rhs.object_; + if (object_ != NULL) { detail::errHandler(retain(), __RETAIN_ERR); } + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + Wrapper(Wrapper&& rhs) CL_HPP_NOEXCEPT + { + object_ = rhs.object_; + rhs.object_ = NULL; + } +#endif + + Wrapper& operator = (const Wrapper& rhs) + { + if (this != &rhs) { + if (object_ != NULL) { detail::errHandler(release(), __RELEASE_ERR); } + object_ = rhs.object_; + if (object_ != NULL) { detail::errHandler(retain(), __RETAIN_ERR); } + } + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + Wrapper& operator = (Wrapper&& rhs) + { + if (this != &rhs) { + if (object_ != NULL) { detail::errHandler(release(), __RELEASE_ERR); } + object_ = rhs.object_; + rhs.object_ = NULL; + } + return *this; + } +#endif + + Wrapper& operator = (const cl_type &rhs) + { + if (object_ != NULL) { detail::errHandler(release(), __RELEASE_ERR); } + object_ = rhs; + return *this; + } + + cl_type operator ()() const { return object_; } + + cl_type& operator ()() { return object_; } + +protected: + template + friend inline cl_int getInfoHelper(Func, cl_uint, U*, int, typename U::cl_type); + + cl_int retain() const + { + return ReferenceHandler::retain(object_); + } + + cl_int release() const + { + return ReferenceHandler::release(object_); + } +}; + +template <> +class Wrapper +{ +public: + typedef cl_device_id cl_type; + +protected: + cl_type object_; + bool referenceCountable_; + + static bool isReferenceCountable(cl_device_id device) + { + bool retVal = false; + if (device != NULL) { + int version = getDevicePlatformVersion(device); + if(version > ((1 << 16) + 1)) { + retVal = true; + } + } + return retVal; + } + +public: + Wrapper() : object_(NULL), referenceCountable_(false) + { + } + + Wrapper(const cl_type &obj) : object_(obj), referenceCountable_(false) + { + referenceCountable_ = isReferenceCountable(obj); + } + + ~Wrapper() + { + if (object_ != NULL) { release(); } + } + + Wrapper(const Wrapper& rhs) + { + object_ = rhs.object_; + referenceCountable_ = isReferenceCountable(object_); + if (object_ != NULL) { detail::errHandler(retain(), __RETAIN_ERR); } + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + Wrapper(Wrapper&& rhs) CL_HPP_NOEXCEPT + { + object_ = rhs.object_; + referenceCountable_ = rhs.referenceCountable_; + rhs.object_ = NULL; + rhs.referenceCountable_ = false; + } +#endif + + Wrapper& operator = (const Wrapper& rhs) + { + if (this != &rhs) { + if (object_ != NULL) { detail::errHandler(release(), __RELEASE_ERR); } + object_ = rhs.object_; + referenceCountable_ = rhs.referenceCountable_; + if (object_ != NULL) { detail::errHandler(retain(), __RETAIN_ERR); } + } + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + Wrapper& operator = (Wrapper&& rhs) + { + if (this != &rhs) { + if (object_ != NULL) { detail::errHandler(release(), __RELEASE_ERR); } + object_ = rhs.object_; + referenceCountable_ = rhs.referenceCountable_; + rhs.object_ = NULL; + rhs.referenceCountable_ = false; + } + return *this; + } +#endif + + Wrapper& operator = (const cl_type &rhs) + { + if (object_ != NULL) { detail::errHandler(release(), __RELEASE_ERR); } + object_ = rhs; + referenceCountable_ = isReferenceCountable(object_); + return *this; + } + + cl_type operator ()() const { return object_; } + + cl_type& operator ()() { return object_; } + +protected: + template + friend inline cl_int getInfoHelper(Func, cl_uint, U*, int, typename U::cl_type); + + template + friend inline cl_int getInfoHelper(Func, cl_uint, VECTOR_CLASS*, int, typename U::cl_type); + + cl_int retain() const + { + if( referenceCountable_ ) { + return ReferenceHandler::retain(object_); + } + else { + return CL_SUCCESS; + } + } + + cl_int release() const + { + if( referenceCountable_ ) { + return ReferenceHandler::release(object_); + } + else { + return CL_SUCCESS; + } + } +}; + +} // namespace detail +//! \endcond + +/*! \stuct ImageFormat + * \brief Adds constructors and member functions for cl_image_format. + * + * \see cl_image_format + */ +struct ImageFormat : public cl_image_format +{ + //! \brief Default constructor - performs no initialization. + ImageFormat(){} + + //! \brief Initializing constructor. + ImageFormat(cl_channel_order order, cl_channel_type type) + { + image_channel_order = order; + image_channel_data_type = type; + } + + //! \brief Assignment operator. + ImageFormat& operator = (const ImageFormat& rhs) + { + if (this != &rhs) { + this->image_channel_data_type = rhs.image_channel_data_type; + this->image_channel_order = rhs.image_channel_order; + } + return *this; + } +}; + +/*! \brief Class interface for cl_device_id. + * + * \note Copies of these objects are inexpensive, since they don't 'own' + * any underlying resources or data structures. + * + * \see cl_device_id + */ +class Device : public detail::Wrapper +{ +public: + //! \brief Default constructor - initializes to NULL. + Device() : detail::Wrapper() { } + + /*! \brief Constructor from cl_device_id. + * + * This simply copies the device ID value, which is an inexpensive operation. + */ + __CL_EXPLICIT_CONSTRUCTORS Device(const cl_device_id &device) : detail::Wrapper(device) { } + + /*! \brief Returns the first device on the default context. + * + * \see Context::getDefault() + */ + static Device getDefault(cl_int * err = NULL); + + /*! \brief Assignment operator from cl_device_id. + * + * This simply copies the device ID value, which is an inexpensive operation. + */ + Device& operator = (const cl_device_id& rhs) + { + detail::Wrapper::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Device(const Device& dev) : detail::Wrapper(dev) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Device& operator = (const Device &dev) + { + detail::Wrapper::operator=(dev); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Device(Device&& dev) CL_HPP_NOEXCEPT : detail::Wrapper(std::move(dev)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Device& operator = (Device &&dev) + { + detail::Wrapper::operator=(std::move(dev)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + + //! \brief Wrapper for clGetDeviceInfo(). + template + cl_int getInfo(cl_device_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetDeviceInfo, object_, name, param), + __GET_DEVICE_INFO_ERR); + } + + //! \brief Wrapper for clGetDeviceInfo() that returns by value. + template typename + detail::param_traits::param_type + getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_device_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if (err != NULL) { + *err = result; + } + return param; + } + + /** + * CL 1.2 version + */ +#if defined(CL_VERSION_1_2) + //! \brief Wrapper for clCreateSubDevicesEXT(). + cl_int createSubDevices( + const cl_device_partition_property * properties, + VECTOR_CLASS* devices) + { + cl_uint n = 0; + cl_int err = clCreateSubDevices(object_, properties, 0, NULL, &n); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __CREATE_SUB_DEVICES); + } + + cl_device_id* ids = (cl_device_id*) alloca(n * sizeof(cl_device_id)); + err = clCreateSubDevices(object_, properties, n, ids, NULL); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __CREATE_SUB_DEVICES); + } + + devices->assign(&ids[0], &ids[n]); + return CL_SUCCESS; + } +#endif // #if defined(CL_VERSION_1_2) + +/** + * CL 1.1 version that uses device fission. + */ +#if defined(CL_VERSION_1_1) +#if defined(USE_CL_DEVICE_FISSION) + cl_int createSubDevices( + const cl_device_partition_property_ext * properties, + VECTOR_CLASS* devices) + { + typedef CL_API_ENTRY cl_int + ( CL_API_CALL * PFN_clCreateSubDevicesEXT)( + cl_device_id /*in_device*/, + const cl_device_partition_property_ext * /* properties */, + cl_uint /*num_entries*/, + cl_device_id * /*out_devices*/, + cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1; + + static PFN_clCreateSubDevicesEXT pfn_clCreateSubDevicesEXT = NULL; + __INIT_CL_EXT_FCN_PTR(clCreateSubDevicesEXT); + + cl_uint n = 0; + cl_int err = pfn_clCreateSubDevicesEXT(object_, properties, 0, NULL, &n); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __CREATE_SUB_DEVICES); + } + + cl_device_id* ids = (cl_device_id*) alloca(n * sizeof(cl_device_id)); + err = pfn_clCreateSubDevicesEXT(object_, properties, n, ids, NULL); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __CREATE_SUB_DEVICES); + } + + devices->assign(&ids[0], &ids[n]); + return CL_SUCCESS; + } +#endif // #if defined(USE_CL_DEVICE_FISSION) +#endif // #if defined(CL_VERSION_1_1) +}; + +/*! \brief Class interface for cl_platform_id. + * + * \note Copies of these objects are inexpensive, since they don't 'own' + * any underlying resources or data structures. + * + * \see cl_platform_id + */ +class Platform : public detail::Wrapper +{ +public: + //! \brief Default constructor - initializes to NULL. + Platform() : detail::Wrapper() { } + + /*! \brief Constructor from cl_platform_id. + * + * This simply copies the platform ID value, which is an inexpensive operation. + */ + __CL_EXPLICIT_CONSTRUCTORS Platform(const cl_platform_id &platform) : detail::Wrapper(platform) { } + + /*! \brief Assignment operator from cl_platform_id. + * + * This simply copies the platform ID value, which is an inexpensive operation. + */ + Platform& operator = (const cl_platform_id& rhs) + { + detail::Wrapper::operator=(rhs); + return *this; + } + + //! \brief Wrapper for clGetPlatformInfo(). + cl_int getInfo(cl_platform_info name, STRING_CLASS* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetPlatformInfo, object_, name, param), + __GET_PLATFORM_INFO_ERR); + } + + //! \brief Wrapper for clGetPlatformInfo() that returns by value. + template typename + detail::param_traits::param_type + getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_platform_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if (err != NULL) { + *err = result; + } + return param; + } + + /*! \brief Gets a list of devices for this platform. + * + * Wraps clGetDeviceIDs(). + */ + cl_int getDevices( + cl_device_type type, + VECTOR_CLASS* devices) const + { + cl_uint n = 0; + if( devices == NULL ) { + return detail::errHandler(CL_INVALID_ARG_VALUE, __GET_DEVICE_IDS_ERR); + } + cl_int err = ::clGetDeviceIDs(object_, type, 0, NULL, &n); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __GET_DEVICE_IDS_ERR); + } + + cl_device_id* ids = (cl_device_id*) alloca(n * sizeof(cl_device_id)); + err = ::clGetDeviceIDs(object_, type, n, ids, NULL); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __GET_DEVICE_IDS_ERR); + } + + devices->assign(&ids[0], &ids[n]); + return CL_SUCCESS; + } + +#if defined(USE_DX_INTEROP) + /*! \brief Get the list of available D3D10 devices. + * + * \param d3d_device_source. + * + * \param d3d_object. + * + * \param d3d_device_set. + * + * \param devices returns a vector of OpenCL D3D10 devices found. The cl::Device + * values returned in devices can be used to identify a specific OpenCL + * device. If \a devices argument is NULL, this argument is ignored. + * + * \return One of the following values: + * - CL_SUCCESS if the function is executed successfully. + * + * The application can query specific capabilities of the OpenCL device(s) + * returned by cl::getDevices. This can be used by the application to + * determine which device(s) to use. + * + * \note In the case that exceptions are enabled and a return value + * other than CL_SUCCESS is generated, then cl::Error exception is + * generated. + */ + cl_int getDevices( + cl_d3d10_device_source_khr d3d_device_source, + void * d3d_object, + cl_d3d10_device_set_khr d3d_device_set, + VECTOR_CLASS* devices) const + { + typedef CL_API_ENTRY cl_int (CL_API_CALL *PFN_clGetDeviceIDsFromD3D10KHR)( + cl_platform_id platform, + cl_d3d10_device_source_khr d3d_device_source, + void * d3d_object, + cl_d3d10_device_set_khr d3d_device_set, + cl_uint num_entries, + cl_device_id * devices, + cl_uint* num_devices); + + if( devices == NULL ) { + return detail::errHandler(CL_INVALID_ARG_VALUE, __GET_DEVICE_IDS_ERR); + } + + static PFN_clGetDeviceIDsFromD3D10KHR pfn_clGetDeviceIDsFromD3D10KHR = NULL; + __INIT_CL_EXT_FCN_PTR_PLATFORM(object_, clGetDeviceIDsFromD3D10KHR); + + cl_uint n = 0; + cl_int err = pfn_clGetDeviceIDsFromD3D10KHR( + object_, + d3d_device_source, + d3d_object, + d3d_device_set, + 0, + NULL, + &n); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __GET_DEVICE_IDS_ERR); + } + + cl_device_id* ids = (cl_device_id*) alloca(n * sizeof(cl_device_id)); + err = pfn_clGetDeviceIDsFromD3D10KHR( + object_, + d3d_device_source, + d3d_object, + d3d_device_set, + n, + ids, + NULL); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __GET_DEVICE_IDS_ERR); + } + + devices->assign(&ids[0], &ids[n]); + return CL_SUCCESS; + } +#endif + + /*! \brief Gets a list of available platforms. + * + * Wraps clGetPlatformIDs(). + */ + static cl_int get( + VECTOR_CLASS* platforms) + { + cl_uint n = 0; + + if( platforms == NULL ) { + return detail::errHandler(CL_INVALID_ARG_VALUE, __GET_PLATFORM_IDS_ERR); + } + + cl_int err = ::clGetPlatformIDs(0, NULL, &n); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __GET_PLATFORM_IDS_ERR); + } + + cl_platform_id* ids = (cl_platform_id*) alloca( + n * sizeof(cl_platform_id)); + err = ::clGetPlatformIDs(n, ids, NULL); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __GET_PLATFORM_IDS_ERR); + } + + platforms->assign(&ids[0], &ids[n]); + return CL_SUCCESS; + } + + /*! \brief Gets the first available platform. + * + * Wraps clGetPlatformIDs(), returning the first result. + */ + static cl_int get( + Platform * platform) + { + cl_uint n = 0; + + if( platform == NULL ) { + return detail::errHandler(CL_INVALID_ARG_VALUE, __GET_PLATFORM_IDS_ERR); + } + + cl_int err = ::clGetPlatformIDs(0, NULL, &n); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __GET_PLATFORM_IDS_ERR); + } + + cl_platform_id* ids = (cl_platform_id*) alloca( + n * sizeof(cl_platform_id)); + err = ::clGetPlatformIDs(n, ids, NULL); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __GET_PLATFORM_IDS_ERR); + } + + *platform = ids[0]; + return CL_SUCCESS; + } + + /*! \brief Gets the first available platform, returning it by value. + * + * Wraps clGetPlatformIDs(), returning the first result. + */ + static Platform get( + cl_int * errResult = NULL) + { + Platform platform; + cl_uint n = 0; + cl_int err = ::clGetPlatformIDs(0, NULL, &n); + if (err != CL_SUCCESS) { + detail::errHandler(err, __GET_PLATFORM_IDS_ERR); + if (errResult != NULL) { + *errResult = err; + } + return Platform(); + } + + cl_platform_id* ids = (cl_platform_id*) alloca( + n * sizeof(cl_platform_id)); + err = ::clGetPlatformIDs(n, ids, NULL); + + if (err != CL_SUCCESS) { + detail::errHandler(err, __GET_PLATFORM_IDS_ERR); + if (errResult != NULL) { + *errResult = err; + } + return Platform(); + } + + + return Platform(ids[0]); + } + + static Platform getDefault( + cl_int *errResult = NULL ) + { + return get(errResult); + } + + +#if defined(CL_VERSION_1_2) + //! \brief Wrapper for clUnloadCompiler(). + cl_int + unloadCompiler() + { + return ::clUnloadPlatformCompiler(object_); + } +#endif // #if defined(CL_VERSION_1_2) +}; // class Platform + +/** + * Deprecated APIs for 1.2 + */ +#if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) || (defined(CL_VERSION_1_1) && !defined(CL_VERSION_1_2)) +/** + * Unload the OpenCL compiler. + * \note Deprecated for OpenCL 1.2. Use Platform::unloadCompiler instead. + */ +inline CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int +UnloadCompiler() CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; +inline cl_int +UnloadCompiler() +{ + return ::clUnloadCompiler(); +} +#endif // #if defined(CL_VERSION_1_1) + +/*! \brief Class interface for cl_context. + * + * \note Copies of these objects are shallow, meaning that the copy will refer + * to the same underlying cl_context as the original. For details, see + * clRetainContext() and clReleaseContext(). + * + * \see cl_context + */ +class Context + : public detail::Wrapper +{ +private: + +#ifdef CL_HPP_CPP11_ATOMICS_SUPPORTED + static std::atomic default_initialized_; +#else // !CL_HPP_CPP11_ATOMICS_SUPPORTED + static volatile int default_initialized_; +#endif // !CL_HPP_CPP11_ATOMICS_SUPPORTED + static Context default_; + static volatile cl_int default_error_; +public: + /*! \brief Constructs a context including a list of specified devices. + * + * Wraps clCreateContext(). + */ + Context( + const VECTOR_CLASS& devices, + cl_context_properties* properties = NULL, + void (CL_CALLBACK * notifyFptr)( + const char *, + const void *, + ::size_t, + void *) = NULL, + void* data = NULL, + cl_int* err = NULL) + { + cl_int error; + + ::size_t numDevices = devices.size(); + cl_device_id* deviceIDs = (cl_device_id*) alloca(numDevices * sizeof(cl_device_id)); + for( ::size_t deviceIndex = 0; deviceIndex < numDevices; ++deviceIndex ) { + deviceIDs[deviceIndex] = (devices[deviceIndex])(); + } + + object_ = ::clCreateContext( + properties, (cl_uint) numDevices, + deviceIDs, + notifyFptr, data, &error); + + detail::errHandler(error, __CREATE_CONTEXT_ERR); + if (err != NULL) { + *err = error; + } + } + + Context( + const Device& device, + cl_context_properties* properties = NULL, + void (CL_CALLBACK * notifyFptr)( + const char *, + const void *, + ::size_t, + void *) = NULL, + void* data = NULL, + cl_int* err = NULL) + { + cl_int error; + + cl_device_id deviceID = device(); + + object_ = ::clCreateContext( + properties, 1, + &deviceID, + notifyFptr, data, &error); + + detail::errHandler(error, __CREATE_CONTEXT_ERR); + if (err != NULL) { + *err = error; + } + } + + /*! \brief Constructs a context including all or a subset of devices of a specified type. + * + * Wraps clCreateContextFromType(). + */ + Context( + cl_device_type type, + cl_context_properties* properties = NULL, + void (CL_CALLBACK * notifyFptr)( + const char *, + const void *, + ::size_t, + void *) = NULL, + void* data = NULL, + cl_int* err = NULL) + { + cl_int error; + +#if !defined(__APPLE__) && !defined(__MACOS) + cl_context_properties prop[4] = {CL_CONTEXT_PLATFORM, 0, 0, 0 }; + + if (properties == NULL) { + // Get a valid platform ID as we cannot send in a blank one + VECTOR_CLASS platforms; + error = Platform::get(&platforms); + if (error != CL_SUCCESS) { + detail::errHandler(error, __CREATE_CONTEXT_FROM_TYPE_ERR); + if (err != NULL) { + *err = error; + } + return; + } + + // Check the platforms we found for a device of our specified type + cl_context_properties platform_id = 0; + for (unsigned int i = 0; i < platforms.size(); i++) { + + VECTOR_CLASS devices; + +#if defined(__CL_ENABLE_EXCEPTIONS) + try { +#endif + + error = platforms[i].getDevices(type, &devices); + +#if defined(__CL_ENABLE_EXCEPTIONS) + } catch (Error) {} + // Catch if exceptions are enabled as we don't want to exit if first platform has no devices of type + // We do error checking next anyway, and can throw there if needed +#endif + + // Only squash CL_SUCCESS and CL_DEVICE_NOT_FOUND + if (error != CL_SUCCESS && error != CL_DEVICE_NOT_FOUND) { + detail::errHandler(error, __CREATE_CONTEXT_FROM_TYPE_ERR); + if (err != NULL) { + *err = error; + } + } + + if (devices.size() > 0) { + platform_id = (cl_context_properties)platforms[i](); + break; + } + } + + if (platform_id == 0) { + detail::errHandler(CL_DEVICE_NOT_FOUND, __CREATE_CONTEXT_FROM_TYPE_ERR); + if (err != NULL) { + *err = CL_DEVICE_NOT_FOUND; + } + return; + } + + prop[1] = platform_id; + properties = &prop[0]; + } +#endif + object_ = ::clCreateContextFromType( + properties, type, notifyFptr, data, &error); + + detail::errHandler(error, __CREATE_CONTEXT_FROM_TYPE_ERR); + if (err != NULL) { + *err = error; + } + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Context(const Context& ctx) : detail::Wrapper(ctx) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Context& operator = (const Context &ctx) + { + detail::Wrapper::operator=(ctx); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Context(Context&& ctx) CL_HPP_NOEXCEPT : detail::Wrapper(std::move(ctx)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Context& operator = (Context &&ctx) + { + detail::Wrapper::operator=(std::move(ctx)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + + /*! \brief Returns a singleton context including all devices of CL_DEVICE_TYPE_DEFAULT. + * + * \note All calls to this function return the same cl_context as the first. + */ + static Context getDefault(cl_int * err = NULL) + { + int state = detail::compare_exchange( + &default_initialized_, + __DEFAULT_BEING_INITIALIZED, __DEFAULT_NOT_INITIALIZED); + + if (state & __DEFAULT_INITIALIZED) { + if (err != NULL) { + *err = default_error_; + } + return default_; + } + + if (state & __DEFAULT_BEING_INITIALIZED) { + // Assume writes will propagate eventually... + while(default_initialized_ != __DEFAULT_INITIALIZED) { + detail::fence(); + } + + if (err != NULL) { + *err = default_error_; + } + return default_; + } + + cl_int error; + default_ = Context( + CL_DEVICE_TYPE_DEFAULT, + NULL, + NULL, + NULL, + &error); + + detail::fence(); + + default_error_ = error; + // Assume writes will propagate eventually... + default_initialized_ = __DEFAULT_INITIALIZED; + + detail::fence(); + + if (err != NULL) { + *err = default_error_; + } + return default_; + + } + + //! \brief Default constructor - initializes to NULL. + Context() : detail::Wrapper() { } + + /*! \brief Constructor from cl_context - takes ownership. + * + * This effectively transfers ownership of a refcount on the cl_context + * into the new Context object. + */ + __CL_EXPLICIT_CONSTRUCTORS Context(const cl_context& context) : detail::Wrapper(context) { } + + /*! \brief Assignment operator from cl_context - takes ownership. + * + * This effectively transfers ownership of a refcount on the rhs and calls + * clReleaseContext() on the value previously held by this instance. + */ + Context& operator = (const cl_context& rhs) + { + detail::Wrapper::operator=(rhs); + return *this; + } + + //! \brief Wrapper for clGetContextInfo(). + template + cl_int getInfo(cl_context_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetContextInfo, object_, name, param), + __GET_CONTEXT_INFO_ERR); + } + + //! \brief Wrapper for clGetContextInfo() that returns by value. + template typename + detail::param_traits::param_type + getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_context_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if (err != NULL) { + *err = result; + } + return param; + } + + /*! \brief Gets a list of supported image formats. + * + * Wraps clGetSupportedImageFormats(). + */ + cl_int getSupportedImageFormats( + cl_mem_flags flags, + cl_mem_object_type type, + VECTOR_CLASS* formats) const + { + cl_uint numEntries; + cl_int err = ::clGetSupportedImageFormats( + object_, + flags, + type, + 0, + NULL, + &numEntries); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __GET_SUPPORTED_IMAGE_FORMATS_ERR); + } + + ImageFormat* value = (ImageFormat*) + alloca(numEntries * sizeof(ImageFormat)); + err = ::clGetSupportedImageFormats( + object_, + flags, + type, + numEntries, + (cl_image_format*) value, + NULL); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __GET_SUPPORTED_IMAGE_FORMATS_ERR); + } + + formats->assign(&value[0], &value[numEntries]); + return CL_SUCCESS; + } +}; + +inline Device Device::getDefault(cl_int * err) +{ + cl_int error; + Device device; + + Context context = Context::getDefault(&error); + detail::errHandler(error, __CREATE_CONTEXT_ERR); + + if (error != CL_SUCCESS) { + if (err != NULL) { + *err = error; + } + } + else { + device = context.getInfo()[0]; + if (err != NULL) { + *err = CL_SUCCESS; + } + } + + return device; +} + + +#ifdef _WIN32 +#ifdef CL_HPP_CPP11_ATOMICS_SUPPORTED +__declspec(selectany) std::atomic Context::default_initialized_; +#else // !CL_HPP_CPP11_ATOMICS_SUPPORTED +__declspec(selectany) volatile int Context::default_initialized_ = __DEFAULT_NOT_INITIALIZED; +#endif // !CL_HPP_CPP11_ATOMICS_SUPPORTED +__declspec(selectany) Context Context::default_; +__declspec(selectany) volatile cl_int Context::default_error_ = CL_SUCCESS; +#else // !_WIN32 +#ifdef CL_HPP_CPP11_ATOMICS_SUPPORTED +__attribute__((weak)) std::atomic Context::default_initialized_; +#else // !CL_HPP_CPP11_ATOMICS_SUPPORTED +__attribute__((weak)) volatile int Context::default_initialized_ = __DEFAULT_NOT_INITIALIZED; +#endif // !CL_HPP_CPP11_ATOMICS_SUPPORTED +__attribute__((weak)) Context Context::default_; +__attribute__((weak)) volatile cl_int Context::default_error_ = CL_SUCCESS; +#endif // !_WIN32 + +/*! \brief Class interface for cl_event. + * + * \note Copies of these objects are shallow, meaning that the copy will refer + * to the same underlying cl_event as the original. For details, see + * clRetainEvent() and clReleaseEvent(). + * + * \see cl_event + */ +class Event : public detail::Wrapper +{ +public: + //! \brief Default constructor - initializes to NULL. + Event() : detail::Wrapper() { } + + /*! \brief Constructor from cl_event - takes ownership. + * + * This effectively transfers ownership of a refcount on the cl_event + * into the new Event object. + */ + __CL_EXPLICIT_CONSTRUCTORS Event(const cl_event& event) : detail::Wrapper(event) { } + + /*! \brief Assignment operator from cl_event - takes ownership. + * + * This effectively transfers ownership of a refcount on the rhs and calls + * clReleaseEvent() on the value previously held by this instance. + */ + Event& operator = (const cl_event& rhs) + { + detail::Wrapper::operator=(rhs); + return *this; + } + + //! \brief Wrapper for clGetEventInfo(). + template + cl_int getInfo(cl_event_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetEventInfo, object_, name, param), + __GET_EVENT_INFO_ERR); + } + + //! \brief Wrapper for clGetEventInfo() that returns by value. + template typename + detail::param_traits::param_type + getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_event_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if (err != NULL) { + *err = result; + } + return param; + } + + //! \brief Wrapper for clGetEventProfilingInfo(). + template + cl_int getProfilingInfo(cl_profiling_info name, T* param) const + { + return detail::errHandler(detail::getInfo( + &::clGetEventProfilingInfo, object_, name, param), + __GET_EVENT_PROFILE_INFO_ERR); + } + + //! \brief Wrapper for clGetEventProfilingInfo() that returns by value. + template typename + detail::param_traits::param_type + getProfilingInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_profiling_info, name>::param_type param; + cl_int result = getProfilingInfo(name, ¶m); + if (err != NULL) { + *err = result; + } + return param; + } + + /*! \brief Blocks the calling thread until this event completes. + * + * Wraps clWaitForEvents(). + */ + cl_int wait() const + { + return detail::errHandler( + ::clWaitForEvents(1, &object_), + __WAIT_FOR_EVENTS_ERR); + } + +#if defined(CL_VERSION_1_1) + /*! \brief Registers a user callback function for a specific command execution status. + * + * Wraps clSetEventCallback(). + */ + cl_int setCallback( + cl_int type, + void (CL_CALLBACK * pfn_notify)(cl_event, cl_int, void *), + void * user_data = NULL) + { + return detail::errHandler( + ::clSetEventCallback( + object_, + type, + pfn_notify, + user_data), + __SET_EVENT_CALLBACK_ERR); + } +#endif + + /*! \brief Blocks the calling thread until every event specified is complete. + * + * Wraps clWaitForEvents(). + */ + static cl_int + waitForEvents(const VECTOR_CLASS& events) + { + return detail::errHandler( + ::clWaitForEvents( + (cl_uint) events.size(), (events.size() > 0) ? (cl_event*)&events.front() : NULL), + __WAIT_FOR_EVENTS_ERR); + } +}; + +#if defined(CL_VERSION_1_1) +/*! \brief Class interface for user events (a subset of cl_event's). + * + * See Event for details about copy semantics, etc. + */ +class UserEvent : public Event +{ +public: + /*! \brief Constructs a user event on a given context. + * + * Wraps clCreateUserEvent(). + */ + UserEvent( + const Context& context, + cl_int * err = NULL) + { + cl_int error; + object_ = ::clCreateUserEvent( + context(), + &error); + + detail::errHandler(error, __CREATE_USER_EVENT_ERR); + if (err != NULL) { + *err = error; + } + } + + //! \brief Default constructor - initializes to NULL. + UserEvent() : Event() { } + + /*! \brief Sets the execution status of a user event object. + * + * Wraps clSetUserEventStatus(). + */ + cl_int setStatus(cl_int status) + { + return detail::errHandler( + ::clSetUserEventStatus(object_,status), + __SET_USER_EVENT_STATUS_ERR); + } +}; +#endif + +/*! \brief Blocks the calling thread until every event specified is complete. + * + * Wraps clWaitForEvents(). + */ +inline static cl_int +WaitForEvents(const VECTOR_CLASS& events) +{ + return detail::errHandler( + ::clWaitForEvents( + (cl_uint) events.size(), (events.size() > 0) ? (cl_event*)&events.front() : NULL), + __WAIT_FOR_EVENTS_ERR); +} + +/*! \brief Class interface for cl_mem. + * + * \note Copies of these objects are shallow, meaning that the copy will refer + * to the same underlying cl_mem as the original. For details, see + * clRetainMemObject() and clReleaseMemObject(). + * + * \see cl_mem + */ +class Memory : public detail::Wrapper +{ +public: + //! \brief Default constructor - initializes to NULL. + Memory() : detail::Wrapper() { } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * This effectively transfers ownership of a refcount on the cl_mem + * into the new Memory object. + */ + __CL_EXPLICIT_CONSTRUCTORS Memory(const cl_mem& memory) : detail::Wrapper(memory) { } + + /*! \brief Assignment operator from cl_mem - takes ownership. + * + * This effectively transfers ownership of a refcount on the rhs and calls + * clReleaseMemObject() on the value previously held by this instance. + */ + Memory& operator = (const cl_mem& rhs) + { + detail::Wrapper::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Memory(const Memory& mem) : detail::Wrapper(mem) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Memory& operator = (const Memory &mem) + { + detail::Wrapper::operator=(mem); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Memory(Memory&& mem) CL_HPP_NOEXCEPT : detail::Wrapper(std::move(mem)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Memory& operator = (Memory &&mem) + { + detail::Wrapper::operator=(std::move(mem)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + + //! \brief Wrapper for clGetMemObjectInfo(). + template + cl_int getInfo(cl_mem_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetMemObjectInfo, object_, name, param), + __GET_MEM_OBJECT_INFO_ERR); + } + + //! \brief Wrapper for clGetMemObjectInfo() that returns by value. + template typename + detail::param_traits::param_type + getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_mem_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if (err != NULL) { + *err = result; + } + return param; + } + +#if defined(CL_VERSION_1_1) + /*! \brief Registers a callback function to be called when the memory object + * is no longer needed. + * + * Wraps clSetMemObjectDestructorCallback(). + * + * Repeated calls to this function, for a given cl_mem value, will append + * to the list of functions called (in reverse order) when memory object's + * resources are freed and the memory object is deleted. + * + * \note + * The registered callbacks are associated with the underlying cl_mem + * value - not the Memory class instance. + */ + cl_int setDestructorCallback( + void (CL_CALLBACK * pfn_notify)(cl_mem, void *), + void * user_data = NULL) + { + return detail::errHandler( + ::clSetMemObjectDestructorCallback( + object_, + pfn_notify, + user_data), + __SET_MEM_OBJECT_DESTRUCTOR_CALLBACK_ERR); + } +#endif + +}; + +// Pre-declare copy functions +class Buffer; +template< typename IteratorType > +cl_int copy( IteratorType startIterator, IteratorType endIterator, cl::Buffer &buffer ); +template< typename IteratorType > +cl_int copy( const cl::Buffer &buffer, IteratorType startIterator, IteratorType endIterator ); +template< typename IteratorType > +cl_int copy( const CommandQueue &queue, IteratorType startIterator, IteratorType endIterator, cl::Buffer &buffer ); +template< typename IteratorType > +cl_int copy( const CommandQueue &queue, const cl::Buffer &buffer, IteratorType startIterator, IteratorType endIterator ); + + +/*! \brief Class interface for Buffer Memory Objects. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class Buffer : public Memory +{ +public: + + /*! \brief Constructs a Buffer in a specified context. + * + * Wraps clCreateBuffer(). + * + * \param host_ptr Storage to be used if the CL_MEM_USE_HOST_PTR flag was + * specified. Note alignment & exclusivity requirements. + */ + Buffer( + const Context& context, + cl_mem_flags flags, + ::size_t size, + void* host_ptr = NULL, + cl_int* err = NULL) + { + cl_int error; + object_ = ::clCreateBuffer(context(), flags, size, host_ptr, &error); + + detail::errHandler(error, __CREATE_BUFFER_ERR); + if (err != NULL) { + *err = error; + } + } + + /*! \brief Constructs a Buffer in the default context. + * + * Wraps clCreateBuffer(). + * + * \param host_ptr Storage to be used if the CL_MEM_USE_HOST_PTR flag was + * specified. Note alignment & exclusivity requirements. + * + * \see Context::getDefault() + */ + Buffer( + cl_mem_flags flags, + ::size_t size, + void* host_ptr = NULL, + cl_int* err = NULL) + { + cl_int error; + + Context context = Context::getDefault(err); + + object_ = ::clCreateBuffer(context(), flags, size, host_ptr, &error); + + detail::errHandler(error, __CREATE_BUFFER_ERR); + if (err != NULL) { + *err = error; + } + } + + /*! + * \brief Construct a Buffer from a host container via iterators. + * IteratorType must be random access. + * If useHostPtr is specified iterators must represent contiguous data. + */ + template< typename IteratorType > + Buffer( + IteratorType startIterator, + IteratorType endIterator, + bool readOnly, + bool useHostPtr = false, + cl_int* err = NULL) + { + typedef typename std::iterator_traits::value_type DataType; + cl_int error; + + cl_mem_flags flags = 0; + if( readOnly ) { + flags |= CL_MEM_READ_ONLY; + } + else { + flags |= CL_MEM_READ_WRITE; + } + if( useHostPtr ) { + flags |= CL_MEM_USE_HOST_PTR; + } + + ::size_t size = sizeof(DataType)*(endIterator - startIterator); + + Context context = Context::getDefault(err); + + if( useHostPtr ) { + object_ = ::clCreateBuffer(context(), flags, size, static_cast(&*startIterator), &error); + } else { + object_ = ::clCreateBuffer(context(), flags, size, 0, &error); + } + + detail::errHandler(error, __CREATE_BUFFER_ERR); + if (err != NULL) { + *err = error; + } + + if( !useHostPtr ) { + error = cl::copy(startIterator, endIterator, *this); + detail::errHandler(error, __CREATE_BUFFER_ERR); + if (err != NULL) { + *err = error; + } + } + } + + /*! + * \brief Construct a Buffer from a host container via iterators using a specified context. + * IteratorType must be random access. + * If useHostPtr is specified iterators must represent contiguous data. + */ + template< typename IteratorType > + Buffer(const Context &context, IteratorType startIterator, IteratorType endIterator, + bool readOnly, bool useHostPtr = false, cl_int* err = NULL); + + /*! + * \brief Construct a Buffer from a host container via iterators using a specified queue. + * If useHostPtr is specified iterators must represent contiguous data. + */ + template< typename IteratorType > + Buffer(const CommandQueue &queue, IteratorType startIterator, IteratorType endIterator, + bool readOnly, bool useHostPtr = false, cl_int* err = NULL); + + //! \brief Default constructor - initializes to NULL. + Buffer() : Memory() { } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * See Memory for further details. + */ + __CL_EXPLICIT_CONSTRUCTORS Buffer(const cl_mem& buffer) : Memory(buffer) { } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + Buffer& operator = (const cl_mem& rhs) + { + Memory::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Buffer(const Buffer& buf) : Memory(buf) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Buffer& operator = (const Buffer &buf) + { + Memory::operator=(buf); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Buffer(Buffer&& buf) CL_HPP_NOEXCEPT : Memory(std::move(buf)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Buffer& operator = (Buffer &&buf) + { + Memory::operator=(std::move(buf)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + +#if defined(CL_VERSION_1_1) + /*! \brief Creates a new buffer object from this. + * + * Wraps clCreateSubBuffer(). + */ + Buffer createSubBuffer( + cl_mem_flags flags, + cl_buffer_create_type buffer_create_type, + const void * buffer_create_info, + cl_int * err = NULL) + { + Buffer result; + cl_int error; + result.object_ = ::clCreateSubBuffer( + object_, + flags, + buffer_create_type, + buffer_create_info, + &error); + + detail::errHandler(error, __CREATE_SUBBUFFER_ERR); + if (err != NULL) { + *err = error; + } + + return result; + } +#endif +}; + +#if defined (USE_DX_INTEROP) +/*! \brief Class interface for creating OpenCL buffers from ID3D10Buffer's. + * + * This is provided to facilitate interoperability with Direct3D. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class BufferD3D10 : public Buffer +{ +public: + typedef CL_API_ENTRY cl_mem (CL_API_CALL *PFN_clCreateFromD3D10BufferKHR)( + cl_context context, cl_mem_flags flags, ID3D10Buffer* buffer, + cl_int* errcode_ret); + + /*! \brief Constructs a BufferD3D10, in a specified context, from a + * given ID3D10Buffer. + * + * Wraps clCreateFromD3D10BufferKHR(). + */ + BufferD3D10( + const Context& context, + cl_mem_flags flags, + ID3D10Buffer* bufobj, + cl_int * err = NULL) + { + static PFN_clCreateFromD3D10BufferKHR pfn_clCreateFromD3D10BufferKHR = NULL; + +#if defined(CL_VERSION_1_2) + vector props = context.getInfo(); + cl_platform platform = -1; + for( int i = 0; i < props.size(); ++i ) { + if( props[i] == CL_CONTEXT_PLATFORM ) { + platform = props[i+1]; + } + } + __INIT_CL_EXT_FCN_PTR_PLATFORM(platform, clCreateFromD3D10BufferKHR); +#endif +#if defined(CL_VERSION_1_1) + __INIT_CL_EXT_FCN_PTR(clCreateFromD3D10BufferKHR); +#endif + + cl_int error; + object_ = pfn_clCreateFromD3D10BufferKHR( + context(), + flags, + bufobj, + &error); + + detail::errHandler(error, __CREATE_GL_BUFFER_ERR); + if (err != NULL) { + *err = error; + } + } + + //! \brief Default constructor - initializes to NULL. + BufferD3D10() : Buffer() { } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * See Memory for further details. + */ + __CL_EXPLICIT_CONSTRUCTORS BufferD3D10(const cl_mem& buffer) : Buffer(buffer) { } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + BufferD3D10& operator = (const cl_mem& rhs) + { + Buffer::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + BufferD3D10(const BufferD3D10& buf) : Buffer(buf) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + BufferD3D10& operator = (const BufferD3D10 &buf) + { + Buffer::operator=(buf); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + BufferD3D10(BufferD3D10&& buf) CL_HPP_NOEXCEPT : Buffer(std::move(buf)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + BufferD3D10& operator = (BufferD3D10 &&buf) + { + Buffer::operator=(std::move(buf)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) +}; +#endif + +/*! \brief Class interface for GL Buffer Memory Objects. + * + * This is provided to facilitate interoperability with OpenGL. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class BufferGL : public Buffer +{ +public: + /*! \brief Constructs a BufferGL in a specified context, from a given + * GL buffer. + * + * Wraps clCreateFromGLBuffer(). + */ + BufferGL( + const Context& context, + cl_mem_flags flags, + cl_GLuint bufobj, + cl_int * err = NULL) + { + cl_int error; + object_ = ::clCreateFromGLBuffer( + context(), + flags, + bufobj, + &error); + + detail::errHandler(error, __CREATE_GL_BUFFER_ERR); + if (err != NULL) { + *err = error; + } + } + + //! \brief Default constructor - initializes to NULL. + BufferGL() : Buffer() { } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * See Memory for further details. + */ + __CL_EXPLICIT_CONSTRUCTORS BufferGL(const cl_mem& buffer) : Buffer(buffer) { } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + BufferGL& operator = (const cl_mem& rhs) + { + Buffer::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + BufferGL(const BufferGL& buf) : Buffer(buf) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + BufferGL& operator = (const BufferGL &buf) + { + Buffer::operator=(buf); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + BufferGL(BufferGL&& buf) CL_HPP_NOEXCEPT : Buffer(std::move(buf)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + BufferGL& operator = (BufferGL &&buf) + { + Buffer::operator=(std::move(buf)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + + //! \brief Wrapper for clGetGLObjectInfo(). + cl_int getObjectInfo( + cl_gl_object_type *type, + cl_GLuint * gl_object_name) + { + return detail::errHandler( + ::clGetGLObjectInfo(object_,type,gl_object_name), + __GET_GL_OBJECT_INFO_ERR); + } +}; + +/*! \brief C++ base class for Image Memory objects. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class Image : public Memory +{ +protected: + //! \brief Default constructor - initializes to NULL. + Image() : Memory() { } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * See Memory for further details. + */ + __CL_EXPLICIT_CONSTRUCTORS Image(const cl_mem& image) : Memory(image) { } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + Image& operator = (const cl_mem& rhs) + { + Memory::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image(const Image& img) : Memory(img) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image& operator = (const Image &img) + { + Memory::operator=(img); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image(Image&& img) CL_HPP_NOEXCEPT : Memory(std::move(img)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image& operator = (Image &&img) + { + Memory::operator=(std::move(img)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + +public: + //! \brief Wrapper for clGetImageInfo(). + template + cl_int getImageInfo(cl_image_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetImageInfo, object_, name, param), + __GET_IMAGE_INFO_ERR); + } + + //! \brief Wrapper for clGetImageInfo() that returns by value. + template typename + detail::param_traits::param_type + getImageInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_image_info, name>::param_type param; + cl_int result = getImageInfo(name, ¶m); + if (err != NULL) { + *err = result; + } + return param; + } +}; + +#if defined(CL_VERSION_1_2) +/*! \brief Class interface for 1D Image Memory objects. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class Image1D : public Image +{ +public: + /*! \brief Constructs a 1D Image in a specified context. + * + * Wraps clCreateImage(). + */ + Image1D( + const Context& context, + cl_mem_flags flags, + ImageFormat format, + ::size_t width, + void* host_ptr = NULL, + cl_int* err = NULL) + { + cl_int error; + cl_image_desc desc = + { + CL_MEM_OBJECT_IMAGE1D, + width, + 0, 0, 0, 0, 0, 0, 0, 0 + }; + object_ = ::clCreateImage( + context(), + flags, + &format, + &desc, + host_ptr, + &error); + + detail::errHandler(error, __CREATE_IMAGE_ERR); + if (err != NULL) { + *err = error; + } + } + + //! \brief Default constructor - initializes to NULL. + Image1D() { } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * See Memory for further details. + */ + __CL_EXPLICIT_CONSTRUCTORS Image1D(const cl_mem& image1D) : Image(image1D) { } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + Image1D& operator = (const cl_mem& rhs) + { + Image::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image1D(const Image1D& img) : Image(img) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image1D& operator = (const Image1D &img) + { + Image::operator=(img); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image1D(Image1D&& img) CL_HPP_NOEXCEPT : Image(std::move(img)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image1D& operator = (Image1D &&img) + { + Image::operator=(std::move(img)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) +}; + +/*! \class Image1DBuffer + * \brief Image interface for 1D buffer images. + */ +class Image1DBuffer : public Image +{ +public: + Image1DBuffer( + const Context& context, + cl_mem_flags flags, + ImageFormat format, + ::size_t width, + const Buffer &buffer, + cl_int* err = NULL) + { + cl_int error; + cl_image_desc desc = + { + CL_MEM_OBJECT_IMAGE1D_BUFFER, + width, + 0, 0, 0, 0, 0, 0, 0, + buffer() + }; + object_ = ::clCreateImage( + context(), + flags, + &format, + &desc, + NULL, + &error); + + detail::errHandler(error, __CREATE_IMAGE_ERR); + if (err != NULL) { + *err = error; + } + } + + Image1DBuffer() { } + + __CL_EXPLICIT_CONSTRUCTORS Image1DBuffer(const cl_mem& image1D) : Image(image1D) { } + + Image1DBuffer& operator = (const cl_mem& rhs) + { + Image::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image1DBuffer(const Image1DBuffer& img) : Image(img) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image1DBuffer& operator = (const Image1DBuffer &img) + { + Image::operator=(img); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image1DBuffer(Image1DBuffer&& img) CL_HPP_NOEXCEPT : Image(std::move(img)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image1DBuffer& operator = (Image1DBuffer &&img) + { + Image::operator=(std::move(img)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) +}; + +/*! \class Image1DArray + * \brief Image interface for arrays of 1D images. + */ +class Image1DArray : public Image +{ +public: + Image1DArray( + const Context& context, + cl_mem_flags flags, + ImageFormat format, + ::size_t arraySize, + ::size_t width, + ::size_t rowPitch, + void* host_ptr = NULL, + cl_int* err = NULL) + { + cl_int error; + cl_image_desc desc = + { + CL_MEM_OBJECT_IMAGE1D_ARRAY, + width, + 0, 0, // height, depth (unused) + arraySize, + rowPitch, + 0, 0, 0, 0 + }; + object_ = ::clCreateImage( + context(), + flags, + &format, + &desc, + host_ptr, + &error); + + detail::errHandler(error, __CREATE_IMAGE_ERR); + if (err != NULL) { + *err = error; + } + } + + Image1DArray() { } + + __CL_EXPLICIT_CONSTRUCTORS Image1DArray(const cl_mem& imageArray) : Image(imageArray) { } + + Image1DArray& operator = (const cl_mem& rhs) + { + Image::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image1DArray(const Image1DArray& img) : Image(img) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image1DArray& operator = (const Image1DArray &img) + { + Image::operator=(img); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image1DArray(Image1DArray&& img) CL_HPP_NOEXCEPT : Image(std::move(img)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image1DArray& operator = (Image1DArray &&img) + { + Image::operator=(std::move(img)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) +}; +#endif // #if defined(CL_VERSION_1_2) + + +/*! \brief Class interface for 2D Image Memory objects. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class Image2D : public Image +{ +public: + /*! \brief Constructs a 1D Image in a specified context. + * + * Wraps clCreateImage(). + */ + Image2D( + const Context& context, + cl_mem_flags flags, + ImageFormat format, + ::size_t width, + ::size_t height, + ::size_t row_pitch = 0, + void* host_ptr = NULL, + cl_int* err = NULL) + { + cl_int error; + bool useCreateImage; + +#if defined(CL_VERSION_1_2) && defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + // Run-time decision based on the actual platform + { + cl_uint version = detail::getContextPlatformVersion(context()); + useCreateImage = (version >= 0x10002); // OpenCL 1.2 or above + } +#elif defined(CL_VERSION_1_2) + useCreateImage = true; +#else + useCreateImage = false; +#endif + +#if defined(CL_VERSION_1_2) + if (useCreateImage) + { + cl_image_desc desc = + { + CL_MEM_OBJECT_IMAGE2D, + width, + height, + 0, 0, // depth, array size (unused) + row_pitch, + 0, 0, 0, 0 + }; + object_ = ::clCreateImage( + context(), + flags, + &format, + &desc, + host_ptr, + &error); + + detail::errHandler(error, __CREATE_IMAGE_ERR); + if (err != NULL) { + *err = error; + } + } +#endif // #if defined(CL_VERSION_1_2) +#if !defined(CL_VERSION_1_2) || defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + if (!useCreateImage) + { + object_ = ::clCreateImage2D( + context(), flags,&format, width, height, row_pitch, host_ptr, &error); + + detail::errHandler(error, __CREATE_IMAGE2D_ERR); + if (err != NULL) { + *err = error; + } + } +#endif // #if !defined(CL_VERSION_1_2) || defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + } + + //! \brief Default constructor - initializes to NULL. + Image2D() { } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * See Memory for further details. + */ + __CL_EXPLICIT_CONSTRUCTORS Image2D(const cl_mem& image2D) : Image(image2D) { } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + Image2D& operator = (const cl_mem& rhs) + { + Image::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image2D(const Image2D& img) : Image(img) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image2D& operator = (const Image2D &img) + { + Image::operator=(img); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image2D(Image2D&& img) CL_HPP_NOEXCEPT : Image(std::move(img)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image2D& operator = (Image2D &&img) + { + Image::operator=(std::move(img)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) +}; + + +#if !defined(CL_VERSION_1_2) +/*! \brief Class interface for GL 2D Image Memory objects. + * + * This is provided to facilitate interoperability with OpenGL. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + * \note Deprecated for OpenCL 1.2. Please use ImageGL instead. + */ +class CL_EXT_PREFIX__VERSION_1_1_DEPRECATED Image2DGL CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED : public Image2D +{ +public: + /*! \brief Constructs an Image2DGL in a specified context, from a given + * GL Texture. + * + * Wraps clCreateFromGLTexture2D(). + */ + Image2DGL( + const Context& context, + cl_mem_flags flags, + cl_GLenum target, + cl_GLint miplevel, + cl_GLuint texobj, + cl_int * err = NULL) + { + cl_int error; + object_ = ::clCreateFromGLTexture2D( + context(), + flags, + target, + miplevel, + texobj, + &error); + + detail::errHandler(error, __CREATE_GL_TEXTURE_2D_ERR); + if (err != NULL) { + *err = error; + } + + } + + //! \brief Default constructor - initializes to NULL. + Image2DGL() : Image2D() { } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * See Memory for further details. + */ + __CL_EXPLICIT_CONSTRUCTORS Image2DGL(const cl_mem& image) : Image2D(image) { } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + Image2DGL& operator = (const cl_mem& rhs) + { + Image2D::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image2DGL(const Image2DGL& img) : Image2D(img) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image2DGL& operator = (const Image2DGL &img) + { + Image2D::operator=(img); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image2DGL(Image2DGL&& img) CL_HPP_NOEXCEPT : Image2D(std::move(img)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image2DGL& operator = (Image2DGL &&img) + { + Image2D::operator=(std::move(img)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) +}; +#endif // #if !defined(CL_VERSION_1_2) + +#if defined(CL_VERSION_1_2) +/*! \class Image2DArray + * \brief Image interface for arrays of 2D images. + */ +class Image2DArray : public Image +{ +public: + Image2DArray( + const Context& context, + cl_mem_flags flags, + ImageFormat format, + ::size_t arraySize, + ::size_t width, + ::size_t height, + ::size_t rowPitch, + ::size_t slicePitch, + void* host_ptr = NULL, + cl_int* err = NULL) + { + cl_int error; + cl_image_desc desc = + { + CL_MEM_OBJECT_IMAGE2D_ARRAY, + width, + height, + 0, // depth (unused) + arraySize, + rowPitch, + slicePitch, + 0, 0, 0 + }; + object_ = ::clCreateImage( + context(), + flags, + &format, + &desc, + host_ptr, + &error); + + detail::errHandler(error, __CREATE_IMAGE_ERR); + if (err != NULL) { + *err = error; + } + } + + Image2DArray() { } + + __CL_EXPLICIT_CONSTRUCTORS Image2DArray(const cl_mem& imageArray) : Image(imageArray) { } + + Image2DArray& operator = (const cl_mem& rhs) + { + Image::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image2DArray(const Image2DArray& img) : Image(img) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image2DArray& operator = (const Image2DArray &img) + { + Image::operator=(img); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image2DArray(Image2DArray&& img) CL_HPP_NOEXCEPT : Image(std::move(img)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image2DArray& operator = (Image2DArray &&img) + { + Image::operator=(std::move(img)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) +}; +#endif // #if defined(CL_VERSION_1_2) + +/*! \brief Class interface for 3D Image Memory objects. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class Image3D : public Image +{ +public: + /*! \brief Constructs a 3D Image in a specified context. + * + * Wraps clCreateImage(). + */ + Image3D( + const Context& context, + cl_mem_flags flags, + ImageFormat format, + ::size_t width, + ::size_t height, + ::size_t depth, + ::size_t row_pitch = 0, + ::size_t slice_pitch = 0, + void* host_ptr = NULL, + cl_int* err = NULL) + { + cl_int error; + bool useCreateImage; + +#if defined(CL_VERSION_1_2) && defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + // Run-time decision based on the actual platform + { + cl_uint version = detail::getContextPlatformVersion(context()); + useCreateImage = (version >= 0x10002); // OpenCL 1.2 or above + } +#elif defined(CL_VERSION_1_2) + useCreateImage = true; +#else + useCreateImage = false; +#endif + +#if defined(CL_VERSION_1_2) + if (useCreateImage) + { + cl_image_desc desc = + { + CL_MEM_OBJECT_IMAGE3D, + width, + height, + depth, + 0, // array size (unused) + row_pitch, + slice_pitch, + 0, 0, 0 + }; + object_ = ::clCreateImage( + context(), + flags, + &format, + &desc, + host_ptr, + &error); + + detail::errHandler(error, __CREATE_IMAGE_ERR); + if (err != NULL) { + *err = error; + } + } +#endif // #if defined(CL_VERSION_1_2) +#if !defined(CL_VERSION_1_2) || defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + if (!useCreateImage) + { + object_ = ::clCreateImage3D( + context(), flags, &format, width, height, depth, row_pitch, + slice_pitch, host_ptr, &error); + + detail::errHandler(error, __CREATE_IMAGE3D_ERR); + if (err != NULL) { + *err = error; + } + } +#endif // #if !defined(CL_VERSION_1_2) || defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + } + + //! \brief Default constructor - initializes to NULL. + Image3D() : Image() { } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * See Memory for further details. + */ + __CL_EXPLICIT_CONSTRUCTORS Image3D(const cl_mem& image3D) : Image(image3D) { } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + Image3D& operator = (const cl_mem& rhs) + { + Image::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image3D(const Image3D& img) : Image(img) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image3D& operator = (const Image3D &img) + { + Image::operator=(img); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image3D(Image3D&& img) CL_HPP_NOEXCEPT : Image(std::move(img)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image3D& operator = (Image3D &&img) + { + Image::operator=(std::move(img)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) +}; + +#if !defined(CL_VERSION_1_2) +/*! \brief Class interface for GL 3D Image Memory objects. + * + * This is provided to facilitate interoperability with OpenGL. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class Image3DGL : public Image3D +{ +public: + /*! \brief Constructs an Image3DGL in a specified context, from a given + * GL Texture. + * + * Wraps clCreateFromGLTexture3D(). + */ + Image3DGL( + const Context& context, + cl_mem_flags flags, + cl_GLenum target, + cl_GLint miplevel, + cl_GLuint texobj, + cl_int * err = NULL) + { + cl_int error; + object_ = ::clCreateFromGLTexture3D( + context(), + flags, + target, + miplevel, + texobj, + &error); + + detail::errHandler(error, __CREATE_GL_TEXTURE_3D_ERR); + if (err != NULL) { + *err = error; + } + } + + //! \brief Default constructor - initializes to NULL. + Image3DGL() : Image3D() { } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * See Memory for further details. + */ + __CL_EXPLICIT_CONSTRUCTORS Image3DGL(const cl_mem& image) : Image3D(image) { } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + Image3DGL& operator = (const cl_mem& rhs) + { + Image3D::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image3DGL(const Image3DGL& img) : Image3D(img) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image3DGL& operator = (const Image3DGL &img) + { + Image3D::operator=(img); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image3DGL(Image3DGL&& img) CL_HPP_NOEXCEPT : Image3D(std::move(img)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image3DGL& operator = (Image3DGL &&img) + { + Image3D::operator=(std::move(img)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) +}; +#endif // #if !defined(CL_VERSION_1_2) + +#if defined(CL_VERSION_1_2) +/*! \class ImageGL + * \brief general image interface for GL interop. + * We abstract the 2D and 3D GL images into a single instance here + * that wraps all GL sourced images on the grounds that setup information + * was performed by OpenCL anyway. + */ +class ImageGL : public Image +{ +public: + ImageGL( + const Context& context, + cl_mem_flags flags, + cl_GLenum target, + cl_GLint miplevel, + cl_GLuint texobj, + cl_int * err = NULL) + { + cl_int error; + object_ = ::clCreateFromGLTexture( + context(), + flags, + target, + miplevel, + texobj, + &error); + + detail::errHandler(error, __CREATE_GL_TEXTURE_ERR); + if (err != NULL) { + *err = error; + } + } + + ImageGL() : Image() { } + + __CL_EXPLICIT_CONSTRUCTORS ImageGL(const cl_mem& image) : Image(image) { } + + ImageGL& operator = (const cl_mem& rhs) + { + Image::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + ImageGL(const ImageGL& img) : Image(img) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + ImageGL& operator = (const ImageGL &img) + { + Image::operator=(img); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + ImageGL(ImageGL&& img) CL_HPP_NOEXCEPT : Image(std::move(img)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + ImageGL& operator = (ImageGL &&img) + { + Image::operator=(std::move(img)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) +}; +#endif // #if defined(CL_VERSION_1_2) + +/*! \brief Class interface for GL Render Buffer Memory Objects. +* +* This is provided to facilitate interoperability with OpenGL. +* +* See Memory for details about copy semantics, etc. +* +* \see Memory +*/ +class BufferRenderGL : +#if defined(CL_VERSION_1_2) + public ImageGL +#else // #if defined(CL_VERSION_1_2) + public Image2DGL +#endif //#if defined(CL_VERSION_1_2) +{ +public: + /*! \brief Constructs a BufferRenderGL in a specified context, from a given + * GL Renderbuffer. + * + * Wraps clCreateFromGLRenderbuffer(). + */ + BufferRenderGL( + const Context& context, + cl_mem_flags flags, + cl_GLuint bufobj, + cl_int * err = NULL) + { + cl_int error; + object_ = ::clCreateFromGLRenderbuffer( + context(), + flags, + bufobj, + &error); + + detail::errHandler(error, __CREATE_GL_RENDER_BUFFER_ERR); + if (err != NULL) { + *err = error; + } + } + + //! \brief Default constructor - initializes to NULL. +#if defined(CL_VERSION_1_2) + BufferRenderGL() : ImageGL() {}; +#else // #if defined(CL_VERSION_1_2) + BufferRenderGL() : Image2DGL() {}; +#endif //#if defined(CL_VERSION_1_2) + + /*! \brief Constructor from cl_mem - takes ownership. + * + * See Memory for further details. + */ +#if defined(CL_VERSION_1_2) + __CL_EXPLICIT_CONSTRUCTORS BufferRenderGL(const cl_mem& buffer) : ImageGL(buffer) { } +#else // #if defined(CL_VERSION_1_2) + __CL_EXPLICIT_CONSTRUCTORS BufferRenderGL(const cl_mem& buffer) : Image2DGL(buffer) { } +#endif //#if defined(CL_VERSION_1_2) + + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + BufferRenderGL& operator = (const cl_mem& rhs) + { +#if defined(CL_VERSION_1_2) + ImageGL::operator=(rhs); +#else // #if defined(CL_VERSION_1_2) + Image2DGL::operator=(rhs); +#endif //#if defined(CL_VERSION_1_2) + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ +#if defined(CL_VERSION_1_2) + BufferRenderGL(const BufferRenderGL& buf) : ImageGL(buf) {} +#else // #if defined(CL_VERSION_1_2) + BufferRenderGL(const BufferRenderGL& buf) : Image2DGL(buf) {} +#endif //#if defined(CL_VERSION_1_2) + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + BufferRenderGL& operator = (const BufferRenderGL &rhs) + { +#if defined(CL_VERSION_1_2) + ImageGL::operator=(rhs); +#else // #if defined(CL_VERSION_1_2) + Image2DGL::operator=(rhs); +#endif //#if defined(CL_VERSION_1_2) + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ +#if defined(CL_VERSION_1_2) + BufferRenderGL(BufferRenderGL&& buf) CL_HPP_NOEXCEPT : ImageGL(std::move(buf)) {} +#else // #if defined(CL_VERSION_1_2) + BufferRenderGL(BufferRenderGL&& buf) CL_HPP_NOEXCEPT : Image2DGL(std::move(buf)) {} +#endif //#if defined(CL_VERSION_1_2) + + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + BufferRenderGL& operator = (BufferRenderGL &&buf) + { +#if defined(CL_VERSION_1_2) + ImageGL::operator=(std::move(buf)); +#else // #if defined(CL_VERSION_1_2) + Image2DGL::operator=(std::move(buf)); +#endif //#if defined(CL_VERSION_1_2) + + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + + //! \brief Wrapper for clGetGLObjectInfo(). + cl_int getObjectInfo( + cl_gl_object_type *type, + cl_GLuint * gl_object_name) + { + return detail::errHandler( + ::clGetGLObjectInfo(object_, type, gl_object_name), + __GET_GL_OBJECT_INFO_ERR); + } +}; + +/*! \brief Class interface for cl_sampler. + * + * \note Copies of these objects are shallow, meaning that the copy will refer + * to the same underlying cl_sampler as the original. For details, see + * clRetainSampler() and clReleaseSampler(). + * + * \see cl_sampler + */ +class Sampler : public detail::Wrapper +{ +public: + //! \brief Default constructor - initializes to NULL. + Sampler() { } + + /*! \brief Constructs a Sampler in a specified context. + * + * Wraps clCreateSampler(). + */ + Sampler( + const Context& context, + cl_bool normalized_coords, + cl_addressing_mode addressing_mode, + cl_filter_mode filter_mode, + cl_int* err = NULL) + { + cl_int error; + object_ = ::clCreateSampler( + context(), + normalized_coords, + addressing_mode, + filter_mode, + &error); + + detail::errHandler(error, __CREATE_SAMPLER_ERR); + if (err != NULL) { + *err = error; + } + } + + /*! \brief Constructor from cl_sampler - takes ownership. + * + * This effectively transfers ownership of a refcount on the cl_sampler + * into the new Sampler object. + */ + __CL_EXPLICIT_CONSTRUCTORS Sampler(const cl_sampler& sampler) : detail::Wrapper(sampler) { } + + /*! \brief Assignment operator from cl_sampler - takes ownership. + * + * This effectively transfers ownership of a refcount on the rhs and calls + * clReleaseSampler() on the value previously held by this instance. + */ + Sampler& operator = (const cl_sampler& rhs) + { + detail::Wrapper::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Sampler(const Sampler& sam) : detail::Wrapper(sam) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Sampler& operator = (const Sampler &sam) + { + detail::Wrapper::operator=(sam); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Sampler(Sampler&& sam) CL_HPP_NOEXCEPT : detail::Wrapper(std::move(sam)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Sampler& operator = (Sampler &&sam) + { + detail::Wrapper::operator=(std::move(sam)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + + //! \brief Wrapper for clGetSamplerInfo(). + template + cl_int getInfo(cl_sampler_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetSamplerInfo, object_, name, param), + __GET_SAMPLER_INFO_ERR); + } + + //! \brief Wrapper for clGetSamplerInfo() that returns by value. + template typename + detail::param_traits::param_type + getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_sampler_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if (err != NULL) { + *err = result; + } + return param; + } +}; + +class Program; +class CommandQueue; +class Kernel; + +//! \brief Class interface for specifying NDRange values. +class NDRange +{ +private: + size_t<3> sizes_; + cl_uint dimensions_; + +public: + //! \brief Default constructor - resulting range has zero dimensions. + NDRange() + : dimensions_(0) + { } + + //! \brief Constructs one-dimensional range. + NDRange(::size_t size0) + : dimensions_(1) + { + sizes_[0] = size0; + } + + //! \brief Constructs two-dimensional range. + NDRange(::size_t size0, ::size_t size1) + : dimensions_(2) + { + sizes_[0] = size0; + sizes_[1] = size1; + } + + //! \brief Constructs three-dimensional range. + NDRange(::size_t size0, ::size_t size1, ::size_t size2) + : dimensions_(3) + { + sizes_[0] = size0; + sizes_[1] = size1; + sizes_[2] = size2; + } + + /*! \brief Conversion operator to const ::size_t *. + * + * \returns a pointer to the size of the first dimension. + */ + operator const ::size_t*() const { + return (const ::size_t*) sizes_; + } + + //! \brief Queries the number of dimensions in the range. + ::size_t dimensions() const { return dimensions_; } +}; + +//! \brief A zero-dimensional range. +static const NDRange NullRange; + +//! \brief Local address wrapper for use with Kernel::setArg +struct LocalSpaceArg +{ + ::size_t size_; +}; + +namespace detail { + +template +struct KernelArgumentHandler +{ + static ::size_t size(const T&) { return sizeof(T); } + static const T* ptr(const T& value) { return &value; } +}; + +template <> +struct KernelArgumentHandler +{ + static ::size_t size(const LocalSpaceArg& value) { return value.size_; } + static const void* ptr(const LocalSpaceArg&) { return NULL; } +}; + +} +//! \endcond + +/*! __local + * \brief Helper function for generating LocalSpaceArg objects. + * Deprecated. Replaced with Local. + */ +inline CL_EXT_PREFIX__VERSION_1_1_DEPRECATED LocalSpaceArg +__local(::size_t size) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; +inline LocalSpaceArg +__local(::size_t size) +{ + LocalSpaceArg ret = { size }; + return ret; +} + +/*! Local + * \brief Helper function for generating LocalSpaceArg objects. + */ +inline LocalSpaceArg +Local(::size_t size) +{ + LocalSpaceArg ret = { size }; + return ret; +} + +//class KernelFunctor; + +/*! \brief Class interface for cl_kernel. + * + * \note Copies of these objects are shallow, meaning that the copy will refer + * to the same underlying cl_kernel as the original. For details, see + * clRetainKernel() and clReleaseKernel(). + * + * \see cl_kernel + */ +class Kernel : public detail::Wrapper +{ +public: + inline Kernel(const Program& program, const char* name, cl_int* err = NULL); + + //! \brief Default constructor - initializes to NULL. + Kernel() { } + + /*! \brief Constructor from cl_kernel - takes ownership. + * + * This effectively transfers ownership of a refcount on the cl_kernel + * into the new Kernel object. + */ + __CL_EXPLICIT_CONSTRUCTORS Kernel(const cl_kernel& kernel) : detail::Wrapper(kernel) { } + + /*! \brief Assignment operator from cl_kernel - takes ownership. + * + * This effectively transfers ownership of a refcount on the rhs and calls + * clReleaseKernel() on the value previously held by this instance. + */ + Kernel& operator = (const cl_kernel& rhs) + { + detail::Wrapper::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Kernel(const Kernel& kernel) : detail::Wrapper(kernel) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Kernel& operator = (const Kernel &kernel) + { + detail::Wrapper::operator=(kernel); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Kernel(Kernel&& kernel) CL_HPP_NOEXCEPT : detail::Wrapper(std::move(kernel)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Kernel& operator = (Kernel &&kernel) + { + detail::Wrapper::operator=(std::move(kernel)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + + template + cl_int getInfo(cl_kernel_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetKernelInfo, object_, name, param), + __GET_KERNEL_INFO_ERR); + } + + template typename + detail::param_traits::param_type + getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_kernel_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if (err != NULL) { + *err = result; + } + return param; + } + +#if defined(CL_VERSION_1_2) + template + cl_int getArgInfo(cl_uint argIndex, cl_kernel_arg_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetKernelArgInfo, object_, argIndex, name, param), + __GET_KERNEL_ARG_INFO_ERR); + } + + template typename + detail::param_traits::param_type + getArgInfo(cl_uint argIndex, cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_kernel_arg_info, name>::param_type param; + cl_int result = getArgInfo(argIndex, name, ¶m); + if (err != NULL) { + *err = result; + } + return param; + } +#endif // #if defined(CL_VERSION_1_2) + + template + cl_int getWorkGroupInfo( + const Device& device, cl_kernel_work_group_info name, T* param) const + { + return detail::errHandler( + detail::getInfo( + &::clGetKernelWorkGroupInfo, object_, device(), name, param), + __GET_KERNEL_WORK_GROUP_INFO_ERR); + } + + template typename + detail::param_traits::param_type + getWorkGroupInfo(const Device& device, cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_kernel_work_group_info, name>::param_type param; + cl_int result = getWorkGroupInfo(device, name, ¶m); + if (err != NULL) { + *err = result; + } + return param; + } + + template + cl_int setArg(cl_uint index, const T &value) + { + return detail::errHandler( + ::clSetKernelArg( + object_, + index, + detail::KernelArgumentHandler::size(value), + detail::KernelArgumentHandler::ptr(value)), + __SET_KERNEL_ARGS_ERR); + } + + cl_int setArg(cl_uint index, ::size_t size, const void* argPtr) + { + return detail::errHandler( + ::clSetKernelArg(object_, index, size, argPtr), + __SET_KERNEL_ARGS_ERR); + } +}; + +/*! \class Program + * \brief Program interface that implements cl_program. + */ +class Program : public detail::Wrapper +{ +public: + typedef VECTOR_CLASS > Binaries; + typedef VECTOR_CLASS > Sources; + + Program( + const STRING_CLASS& source, + bool build = false, + cl_int* err = NULL) + { + cl_int error; + + const char * strings = source.c_str(); + const ::size_t length = source.size(); + + Context context = Context::getDefault(err); + + object_ = ::clCreateProgramWithSource( + context(), (cl_uint)1, &strings, &length, &error); + + detail::errHandler(error, __CREATE_PROGRAM_WITH_SOURCE_ERR); + + if (error == CL_SUCCESS && build) { + + error = ::clBuildProgram( + object_, + 0, + NULL, + "", + NULL, + NULL); + + detail::errHandler(error, __BUILD_PROGRAM_ERR); + } + + if (err != NULL) { + *err = error; + } + } + + Program( + const Context& context, + const STRING_CLASS& source, + bool build = false, + cl_int* err = NULL) + { + cl_int error; + + const char * strings = source.c_str(); + const ::size_t length = source.size(); + + object_ = ::clCreateProgramWithSource( + context(), (cl_uint)1, &strings, &length, &error); + + detail::errHandler(error, __CREATE_PROGRAM_WITH_SOURCE_ERR); + + if (error == CL_SUCCESS && build) { + + error = ::clBuildProgram( + object_, + 0, + NULL, + "", + NULL, + NULL); + + detail::errHandler(error, __BUILD_PROGRAM_ERR); + } + + if (err != NULL) { + *err = error; + } + } + + Program( + const Context& context, + const Sources& sources, + cl_int* err = NULL) + { + cl_int error; + + const ::size_t n = (::size_t)sources.size(); + ::size_t* lengths = (::size_t*) alloca(n * sizeof(::size_t)); + const char** strings = (const char**) alloca(n * sizeof(const char*)); + + for (::size_t i = 0; i < n; ++i) { + strings[i] = sources[(int)i].first; + lengths[i] = sources[(int)i].second; + } + + object_ = ::clCreateProgramWithSource( + context(), (cl_uint)n, strings, lengths, &error); + + detail::errHandler(error, __CREATE_PROGRAM_WITH_SOURCE_ERR); + if (err != NULL) { + *err = error; + } + } + + /** + * Construct a program object from a list of devices and a per-device list of binaries. + * \param context A valid OpenCL context in which to construct the program. + * \param devices A vector of OpenCL device objects for which the program will be created. + * \param binaries A vector of pairs of a pointer to a binary object and its length. + * \param binaryStatus An optional vector that on completion will be resized to + * match the size of binaries and filled with values to specify if each binary + * was successfully loaded. + * Set to CL_SUCCESS if the binary was successfully loaded. + * Set to CL_INVALID_VALUE if the length is 0 or the binary pointer is NULL. + * Set to CL_INVALID_BINARY if the binary provided is not valid for the matching device. + * \param err if non-NULL will be set to CL_SUCCESS on successful operation or one of the following errors: + * CL_INVALID_CONTEXT if context is not a valid context. + * CL_INVALID_VALUE if the length of devices is zero; or if the length of binaries does not match the length of devices; + * or if any entry in binaries is NULL or has length 0. + * CL_INVALID_DEVICE if OpenCL devices listed in devices are not in the list of devices associated with context. + * CL_INVALID_BINARY if an invalid program binary was encountered for any device. binaryStatus will return specific status for each device. + * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by the OpenCL implementation on the host. + */ + Program( + const Context& context, + const VECTOR_CLASS& devices, + const Binaries& binaries, + VECTOR_CLASS* binaryStatus = NULL, + cl_int* err = NULL) + { + cl_int error; + + const ::size_t numDevices = devices.size(); + + // Catch size mismatch early and return + if(binaries.size() != numDevices) { + error = CL_INVALID_VALUE; + detail::errHandler(error, __CREATE_PROGRAM_WITH_BINARY_ERR); + if (err != NULL) { + *err = error; + } + return; + } + + ::size_t* lengths = (::size_t*) alloca(numDevices * sizeof(::size_t)); + const unsigned char** images = (const unsigned char**) alloca(numDevices * sizeof(const unsigned char**)); + + for (::size_t i = 0; i < numDevices; ++i) { + images[i] = (const unsigned char*)binaries[i].first; + lengths[i] = binaries[(int)i].second; + } + + cl_device_id* deviceIDs = (cl_device_id*) alloca(numDevices * sizeof(cl_device_id)); + for( ::size_t deviceIndex = 0; deviceIndex < numDevices; ++deviceIndex ) { + deviceIDs[deviceIndex] = (devices[deviceIndex])(); + } + + if(binaryStatus) { + binaryStatus->resize(numDevices); + } + + object_ = ::clCreateProgramWithBinary( + context(), (cl_uint) devices.size(), + deviceIDs, + lengths, images, (binaryStatus != NULL && numDevices > 0) + ? &binaryStatus->front() + : NULL, &error); + + detail::errHandler(error, __CREATE_PROGRAM_WITH_BINARY_ERR); + if (err != NULL) { + *err = error; + } + } + + +#if defined(CL_VERSION_1_2) + /** + * Create program using builtin kernels. + * \param kernelNames Semi-colon separated list of builtin kernel names + */ + Program( + const Context& context, + const VECTOR_CLASS& devices, + const STRING_CLASS& kernelNames, + cl_int* err = NULL) + { + cl_int error; + + + ::size_t numDevices = devices.size(); + cl_device_id* deviceIDs = (cl_device_id*) alloca(numDevices * sizeof(cl_device_id)); + for( ::size_t deviceIndex = 0; deviceIndex < numDevices; ++deviceIndex ) { + deviceIDs[deviceIndex] = (devices[deviceIndex])(); + } + + object_ = ::clCreateProgramWithBuiltInKernels( + context(), + (cl_uint) devices.size(), + deviceIDs, + kernelNames.c_str(), + &error); + + detail::errHandler(error, __CREATE_PROGRAM_WITH_BUILT_IN_KERNELS_ERR); + if (err != NULL) { + *err = error; + } + } +#endif // #if defined(CL_VERSION_1_2) + + Program() { } + + __CL_EXPLICIT_CONSTRUCTORS Program(const cl_program& program) : detail::Wrapper(program) { } + + Program& operator = (const cl_program& rhs) + { + detail::Wrapper::operator=(rhs); + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Program(const Program& program) : detail::Wrapper(program) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Program& operator = (const Program &program) + { + detail::Wrapper::operator=(program); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Program(Program&& program) CL_HPP_NOEXCEPT : detail::Wrapper(std::move(program)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Program& operator = (Program &&program) + { + detail::Wrapper::operator=(std::move(program)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + + cl_int build( + const VECTOR_CLASS& devices, + const char* options = NULL, + void (CL_CALLBACK * notifyFptr)(cl_program, void *) = NULL, + void* data = NULL) const + { + ::size_t numDevices = devices.size(); + cl_device_id* deviceIDs = (cl_device_id*) alloca(numDevices * sizeof(cl_device_id)); + for( ::size_t deviceIndex = 0; deviceIndex < numDevices; ++deviceIndex ) { + deviceIDs[deviceIndex] = (devices[deviceIndex])(); + } + + return detail::errHandler( + ::clBuildProgram( + object_, + (cl_uint) + devices.size(), + deviceIDs, + options, + notifyFptr, + data), + __BUILD_PROGRAM_ERR); + } + + cl_int build( + const char* options = NULL, + void (CL_CALLBACK * notifyFptr)(cl_program, void *) = NULL, + void* data = NULL) const + { + return detail::errHandler( + ::clBuildProgram( + object_, + 0, + NULL, + options, + notifyFptr, + data), + __BUILD_PROGRAM_ERR); + } + +#if defined(CL_VERSION_1_2) + cl_int compile( + const char* options = NULL, + void (CL_CALLBACK * notifyFptr)(cl_program, void *) = NULL, + void* data = NULL) const + { + return detail::errHandler( + ::clCompileProgram( + object_, + 0, + NULL, + options, + 0, + NULL, + NULL, + notifyFptr, + data), + __COMPILE_PROGRAM_ERR); + } +#endif + + template + cl_int getInfo(cl_program_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetProgramInfo, object_, name, param), + __GET_PROGRAM_INFO_ERR); + } + + template typename + detail::param_traits::param_type + getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_program_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if (err != NULL) { + *err = result; + } + return param; + } + + template + cl_int getBuildInfo( + const Device& device, cl_program_build_info name, T* param) const + { + return detail::errHandler( + detail::getInfo( + &::clGetProgramBuildInfo, object_, device(), name, param), + __GET_PROGRAM_BUILD_INFO_ERR); + } + + template typename + detail::param_traits::param_type + getBuildInfo(const Device& device, cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_program_build_info, name>::param_type param; + cl_int result = getBuildInfo(device, name, ¶m); + if (err != NULL) { + *err = result; + } + return param; + } + + cl_int createKernels(VECTOR_CLASS* kernels) + { + cl_uint numKernels; + cl_int err = ::clCreateKernelsInProgram(object_, 0, NULL, &numKernels); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __CREATE_KERNELS_IN_PROGRAM_ERR); + } + + Kernel* value = (Kernel*) alloca(numKernels * sizeof(Kernel)); + err = ::clCreateKernelsInProgram( + object_, numKernels, (cl_kernel*) value, NULL); + if (err != CL_SUCCESS) { + return detail::errHandler(err, __CREATE_KERNELS_IN_PROGRAM_ERR); + } + + kernels->assign(&value[0], &value[numKernels]); + return CL_SUCCESS; + } +}; + +#if defined(CL_VERSION_1_2) +inline Program linkProgram( + Program input1, + Program input2, + const char* options = NULL, + void (CL_CALLBACK * notifyFptr)(cl_program, void *) = NULL, + void* data = NULL, + cl_int* err = NULL) +{ + cl_int error_local = CL_SUCCESS; + + cl_program programs[2] = { input1(), input2() }; + + Context ctx = input1.getInfo(&error_local); + if(error_local!=CL_SUCCESS) { + detail::errHandler(error_local, __LINK_PROGRAM_ERR); + } + + cl_program prog = ::clLinkProgram( + ctx(), + 0, + NULL, + options, + 2, + programs, + notifyFptr, + data, + &error_local); + + detail::errHandler(error_local,__COMPILE_PROGRAM_ERR); + if (err != NULL) { + *err = error_local; + } + + return Program(prog); +} + +inline Program linkProgram( + VECTOR_CLASS inputPrograms, + const char* options = NULL, + void (CL_CALLBACK * notifyFptr)(cl_program, void *) = NULL, + void* data = NULL, + cl_int* err = NULL) +{ + cl_int error_local = CL_SUCCESS; + + cl_program * programs = (cl_program*) alloca(inputPrograms.size() * sizeof(cl_program)); + + if (programs != NULL) { + for (unsigned int i = 0; i < inputPrograms.size(); i++) { + programs[i] = inputPrograms[i](); + } + } + + Context ctx; + if(inputPrograms.size() > 0) { + ctx = inputPrograms[0].getInfo(&error_local); + if(error_local!=CL_SUCCESS) { + detail::errHandler(error_local, __LINK_PROGRAM_ERR); + } + } + cl_program prog = ::clLinkProgram( + ctx(), + 0, + NULL, + options, + (cl_uint)inputPrograms.size(), + programs, + notifyFptr, + data, + &error_local); + + detail::errHandler(error_local,__COMPILE_PROGRAM_ERR); + if (err != NULL) { + *err = error_local; + } + + return Program(prog); +} +#endif + +template<> +inline VECTOR_CLASS cl::Program::getInfo(cl_int* err) const +{ + VECTOR_CLASS< ::size_t> sizes = getInfo(); + VECTOR_CLASS binaries; + for (VECTOR_CLASS< ::size_t>::iterator s = sizes.begin(); s != sizes.end(); ++s) + { + char *ptr = NULL; + if (*s != 0) + ptr = new char[*s]; + binaries.push_back(ptr); + } + + cl_int result = getInfo(CL_PROGRAM_BINARIES, &binaries); + if (err != NULL) { + *err = result; + } + return binaries; +} + +inline Kernel::Kernel(const Program& program, const char* name, cl_int* err) +{ + cl_int error; + + object_ = ::clCreateKernel(program(), name, &error); + detail::errHandler(error, __CREATE_KERNEL_ERR); + + if (err != NULL) { + *err = error; + } + +} + +/*! \class CommandQueue + * \brief CommandQueue interface for cl_command_queue. + */ +class CommandQueue : public detail::Wrapper +{ +private: +#ifdef CL_HPP_CPP11_ATOMICS_SUPPORTED + static std::atomic default_initialized_; +#else // !CL_HPP_CPP11_ATOMICS_SUPPORTED + static volatile int default_initialized_; +#endif // !CL_HPP_CPP11_ATOMICS_SUPPORTED + static CommandQueue default_; + static volatile cl_int default_error_; +public: + CommandQueue( + cl_command_queue_properties properties, + cl_int* err = NULL) + { + cl_int error; + + Context context = Context::getDefault(&error); + detail::errHandler(error, __CREATE_CONTEXT_ERR); + + if (error != CL_SUCCESS) { + if (err != NULL) { + *err = error; + } + } + else { + Device device = context.getInfo()[0]; + + object_ = ::clCreateCommandQueue( + context(), device(), properties, &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_ERR); + if (err != NULL) { + *err = error; + } + } + } + /*! + * \brief Constructs a CommandQueue for an implementation defined device in the given context + */ + explicit CommandQueue( + const Context& context, + cl_command_queue_properties properties = 0, + cl_int* err = NULL) + { + cl_int error; + VECTOR_CLASS devices; + error = context.getInfo(CL_CONTEXT_DEVICES, &devices); + + detail::errHandler(error, __CREATE_CONTEXT_ERR); + + if (error != CL_SUCCESS) + { + if (err != NULL) { + *err = error; + } + return; + } + + object_ = ::clCreateCommandQueue(context(), devices[0](), properties, &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_ERR); + + if (err != NULL) { + *err = error; + } + + } + + CommandQueue( + const Context& context, + const Device& device, + cl_command_queue_properties properties = 0, + cl_int* err = NULL) + { + cl_int error; + object_ = ::clCreateCommandQueue( + context(), device(), properties, &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_ERR); + if (err != NULL) { + *err = error; + } + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + CommandQueue(const CommandQueue& queue) : detail::Wrapper(queue) {} + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + CommandQueue& operator = (const CommandQueue &queue) + { + detail::Wrapper::operator=(queue); + return *this; + } + +#if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + CommandQueue(CommandQueue&& queue) CL_HPP_NOEXCEPT : detail::Wrapper(std::move(queue)) {} + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + CommandQueue& operator = (CommandQueue &&queue) + { + detail::Wrapper::operator=(std::move(queue)); + return *this; + } +#endif // #if defined(CL_HPP_RVALUE_REFERENCES_SUPPORTED) + + static CommandQueue getDefault(cl_int * err = NULL) + { + int state = detail::compare_exchange( + &default_initialized_, + __DEFAULT_BEING_INITIALIZED, __DEFAULT_NOT_INITIALIZED); + + if (state & __DEFAULT_INITIALIZED) { + if (err != NULL) { + *err = default_error_; + } + return default_; + } + + if (state & __DEFAULT_BEING_INITIALIZED) { + // Assume writes will propagate eventually... + while(default_initialized_ != __DEFAULT_INITIALIZED) { + detail::fence(); + } + + if (err != NULL) { + *err = default_error_; + } + return default_; + } + + cl_int error; + + Context context = Context::getDefault(&error); + detail::errHandler(error, __CREATE_COMMAND_QUEUE_ERR); + + if (error != CL_SUCCESS) { + if (err != NULL) { + *err = error; + } + } + else { + Device device = context.getInfo()[0]; + + default_ = CommandQueue(context, device, 0, &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_ERR); + if (err != NULL) { + *err = error; + } + } + + detail::fence(); + + default_error_ = error; + // Assume writes will propagate eventually... + default_initialized_ = __DEFAULT_INITIALIZED; + + detail::fence(); + + if (err != NULL) { + *err = default_error_; + } + return default_; + + } + + CommandQueue() { } + + __CL_EXPLICIT_CONSTRUCTORS CommandQueue(const cl_command_queue& commandQueue) : detail::Wrapper(commandQueue) { } + + CommandQueue& operator = (const cl_command_queue& rhs) + { + detail::Wrapper::operator=(rhs); + return *this; + } + + template + cl_int getInfo(cl_command_queue_info name, T* param) const + { + return detail::errHandler( + detail::getInfo( + &::clGetCommandQueueInfo, object_, name, param), + __GET_COMMAND_QUEUE_INFO_ERR); + } + + template typename + detail::param_traits::param_type + getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_command_queue_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if (err != NULL) { + *err = result; + } + return param; + } + + cl_int enqueueReadBuffer( + const Buffer& buffer, + cl_bool blocking, + ::size_t offset, + ::size_t size, + void* ptr, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueReadBuffer( + object_, buffer(), blocking, offset, size, + ptr, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_READ_BUFFER_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + cl_int enqueueWriteBuffer( + const Buffer& buffer, + cl_bool blocking, + ::size_t offset, + ::size_t size, + const void* ptr, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueWriteBuffer( + object_, buffer(), blocking, offset, size, + ptr, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_WRITE_BUFFER_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + cl_int enqueueCopyBuffer( + const Buffer& src, + const Buffer& dst, + ::size_t src_offset, + ::size_t dst_offset, + ::size_t size, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueCopyBuffer( + object_, src(), dst(), src_offset, dst_offset, size, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQEUE_COPY_BUFFER_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + cl_int enqueueReadBufferRect( + const Buffer& buffer, + cl_bool blocking, + const size_t<3>& buffer_offset, + const size_t<3>& host_offset, + const size_t<3>& region, + ::size_t buffer_row_pitch, + ::size_t buffer_slice_pitch, + ::size_t host_row_pitch, + ::size_t host_slice_pitch, + void *ptr, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueReadBufferRect( + object_, + buffer(), + blocking, + (const ::size_t *)buffer_offset, + (const ::size_t *)host_offset, + (const ::size_t *)region, + buffer_row_pitch, + buffer_slice_pitch, + host_row_pitch, + host_slice_pitch, + ptr, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_READ_BUFFER_RECT_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + cl_int enqueueWriteBufferRect( + const Buffer& buffer, + cl_bool blocking, + const size_t<3>& buffer_offset, + const size_t<3>& host_offset, + const size_t<3>& region, + ::size_t buffer_row_pitch, + ::size_t buffer_slice_pitch, + ::size_t host_row_pitch, + ::size_t host_slice_pitch, + void *ptr, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueWriteBufferRect( + object_, + buffer(), + blocking, + (const ::size_t *)buffer_offset, + (const ::size_t *)host_offset, + (const ::size_t *)region, + buffer_row_pitch, + buffer_slice_pitch, + host_row_pitch, + host_slice_pitch, + ptr, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_WRITE_BUFFER_RECT_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + cl_int enqueueCopyBufferRect( + const Buffer& src, + const Buffer& dst, + const size_t<3>& src_origin, + const size_t<3>& dst_origin, + const size_t<3>& region, + ::size_t src_row_pitch, + ::size_t src_slice_pitch, + ::size_t dst_row_pitch, + ::size_t dst_slice_pitch, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueCopyBufferRect( + object_, + src(), + dst(), + (const ::size_t *)src_origin, + (const ::size_t *)dst_origin, + (const ::size_t *)region, + src_row_pitch, + src_slice_pitch, + dst_row_pitch, + dst_slice_pitch, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQEUE_COPY_BUFFER_RECT_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + +#if defined(CL_VERSION_1_2) + /** + * Enqueue a command to fill a buffer object with a pattern + * of a given size. The pattern is specified a as vector. + * \tparam PatternType The datatype of the pattern field. + * The pattern type must be an accepted OpenCL data type. + */ + template + cl_int enqueueFillBuffer( + const Buffer& buffer, + PatternType pattern, + ::size_t offset, + ::size_t size, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueFillBuffer( + object_, + buffer(), + static_cast(&pattern), + sizeof(PatternType), + offset, + size, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_FILL_BUFFER_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } +#endif // #if defined(CL_VERSION_1_2) + + cl_int enqueueReadImage( + const Image& image, + cl_bool blocking, + const size_t<3>& origin, + const size_t<3>& region, + ::size_t row_pitch, + ::size_t slice_pitch, + void* ptr, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueReadImage( + object_, image(), blocking, (const ::size_t *) origin, + (const ::size_t *) region, row_pitch, slice_pitch, ptr, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_READ_IMAGE_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + cl_int enqueueWriteImage( + const Image& image, + cl_bool blocking, + const size_t<3>& origin, + const size_t<3>& region, + ::size_t row_pitch, + ::size_t slice_pitch, + void* ptr, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueWriteImage( + object_, image(), blocking, (const ::size_t *) origin, + (const ::size_t *) region, row_pitch, slice_pitch, ptr, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_WRITE_IMAGE_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + cl_int enqueueCopyImage( + const Image& src, + const Image& dst, + const size_t<3>& src_origin, + const size_t<3>& dst_origin, + const size_t<3>& region, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueCopyImage( + object_, src(), dst(), (const ::size_t *) src_origin, + (const ::size_t *)dst_origin, (const ::size_t *) region, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_COPY_IMAGE_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + +#if defined(CL_VERSION_1_2) + /** + * Enqueue a command to fill an image object with a specified color. + * \param fillColor is the color to use to fill the image. + * This is a four component RGBA floating-point color value if + * the image channel data type is not an unnormalized signed or + * unsigned data type. + */ + cl_int enqueueFillImage( + const Image& image, + cl_float4 fillColor, + const size_t<3>& origin, + const size_t<3>& region, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueFillImage( + object_, + image(), + static_cast(&fillColor), + (const ::size_t *) origin, + (const ::size_t *) region, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_FILL_IMAGE_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + /** + * Enqueue a command to fill an image object with a specified color. + * \param fillColor is the color to use to fill the image. + * This is a four component RGBA signed integer color value if + * the image channel data type is an unnormalized signed integer + * type. + */ + cl_int enqueueFillImage( + const Image& image, + cl_int4 fillColor, + const size_t<3>& origin, + const size_t<3>& region, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueFillImage( + object_, + image(), + static_cast(&fillColor), + (const ::size_t *) origin, + (const ::size_t *) region, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_FILL_IMAGE_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + /** + * Enqueue a command to fill an image object with a specified color. + * \param fillColor is the color to use to fill the image. + * This is a four component RGBA unsigned integer color value if + * the image channel data type is an unnormalized unsigned integer + * type. + */ + cl_int enqueueFillImage( + const Image& image, + cl_uint4 fillColor, + const size_t<3>& origin, + const size_t<3>& region, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueFillImage( + object_, + image(), + static_cast(&fillColor), + (const ::size_t *) origin, + (const ::size_t *) region, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_FILL_IMAGE_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } +#endif // #if defined(CL_VERSION_1_2) + + cl_int enqueueCopyImageToBuffer( + const Image& src, + const Buffer& dst, + const size_t<3>& src_origin, + const size_t<3>& region, + ::size_t dst_offset, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueCopyImageToBuffer( + object_, src(), dst(), (const ::size_t *) src_origin, + (const ::size_t *) region, dst_offset, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_COPY_IMAGE_TO_BUFFER_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + cl_int enqueueCopyBufferToImage( + const Buffer& src, + const Image& dst, + ::size_t src_offset, + const size_t<3>& dst_origin, + const size_t<3>& region, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueCopyBufferToImage( + object_, src(), dst(), src_offset, + (const ::size_t *) dst_origin, (const ::size_t *) region, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_COPY_BUFFER_TO_IMAGE_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + void* enqueueMapBuffer( + const Buffer& buffer, + cl_bool blocking, + cl_map_flags flags, + ::size_t offset, + ::size_t size, + const VECTOR_CLASS* events = NULL, + Event* event = NULL, + cl_int* err = NULL) const + { + cl_event tmp; + cl_int error; + void * result = ::clEnqueueMapBuffer( + object_, buffer(), blocking, flags, offset, size, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL, + &error); + + detail::errHandler(error, __ENQUEUE_MAP_BUFFER_ERR); + if (err != NULL) { + *err = error; + } + if (event != NULL && error == CL_SUCCESS) + *event = tmp; + + return result; + } + + void* enqueueMapImage( + const Image& buffer, + cl_bool blocking, + cl_map_flags flags, + const size_t<3>& origin, + const size_t<3>& region, + ::size_t * row_pitch, + ::size_t * slice_pitch, + const VECTOR_CLASS* events = NULL, + Event* event = NULL, + cl_int* err = NULL) const + { + cl_event tmp; + cl_int error; + void * result = ::clEnqueueMapImage( + object_, buffer(), blocking, flags, + (const ::size_t *) origin, (const ::size_t *) region, + row_pitch, slice_pitch, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL, + &error); + + detail::errHandler(error, __ENQUEUE_MAP_IMAGE_ERR); + if (err != NULL) { + *err = error; + } + if (event != NULL && error == CL_SUCCESS) + *event = tmp; + return result; + } + + cl_int enqueueUnmapMemObject( + const Memory& memory, + void* mapped_ptr, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueUnmapMemObject( + object_, memory(), mapped_ptr, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_UNMAP_MEM_OBJECT_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + +#if defined(CL_VERSION_1_2) + /** + * Enqueues a marker command which waits for either a list of events to complete, + * or all previously enqueued commands to complete. + * + * Enqueues a marker command which waits for either a list of events to complete, + * or if the list is empty it waits for all commands previously enqueued in command_queue + * to complete before it completes. This command returns an event which can be waited on, + * i.e. this event can be waited on to insure that all events either in the event_wait_list + * or all previously enqueued commands, queued before this command to command_queue, + * have completed. + */ + cl_int enqueueMarkerWithWaitList( + const VECTOR_CLASS *events = 0, + Event *event = 0) + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueMarkerWithWaitList( + object_, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_MARKER_WAIT_LIST_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + /** + * A synchronization point that enqueues a barrier operation. + * + * Enqueues a barrier command which waits for either a list of events to complete, + * or if the list is empty it waits for all commands previously enqueued in command_queue + * to complete before it completes. This command blocks command execution, that is, any + * following commands enqueued after it do not execute until it completes. This command + * returns an event which can be waited on, i.e. this event can be waited on to insure that + * all events either in the event_wait_list or all previously enqueued commands, queued + * before this command to command_queue, have completed. + */ + cl_int enqueueBarrierWithWaitList( + const VECTOR_CLASS *events = 0, + Event *event = 0) + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueBarrierWithWaitList( + object_, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_BARRIER_WAIT_LIST_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + /** + * Enqueues a command to indicate with which device a set of memory objects + * should be associated. + */ + cl_int enqueueMigrateMemObjects( + const VECTOR_CLASS &memObjects, + cl_mem_migration_flags flags, + const VECTOR_CLASS* events = NULL, + Event* event = NULL + ) + { + cl_event tmp; + + cl_mem* localMemObjects = static_cast(alloca(memObjects.size() * sizeof(cl_mem))); + for( int i = 0; i < (int)memObjects.size(); ++i ) { + localMemObjects[i] = memObjects[i](); + } + + + cl_int err = detail::errHandler( + ::clEnqueueMigrateMemObjects( + object_, + (cl_uint)memObjects.size(), + static_cast(localMemObjects), + flags, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_UNMAP_MEM_OBJECT_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } +#endif // #if defined(CL_VERSION_1_2) + + cl_int enqueueNDRangeKernel( + const Kernel& kernel, + const NDRange& offset, + const NDRange& global, + const NDRange& local = NullRange, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueNDRangeKernel( + object_, kernel(), (cl_uint) global.dimensions(), + offset.dimensions() != 0 ? (const ::size_t*) offset : NULL, + (const ::size_t*) global, + local.dimensions() != 0 ? (const ::size_t*) local : NULL, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_NDRANGE_KERNEL_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + cl_int enqueueTask( + const Kernel& kernel, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueTask( + object_, kernel(), + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_TASK_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + cl_int enqueueNativeKernel( + void (CL_CALLBACK *userFptr)(void *), + std::pair args, + const VECTOR_CLASS* mem_objects = NULL, + const VECTOR_CLASS* mem_locs = NULL, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_mem * mems = (mem_objects != NULL && mem_objects->size() > 0) + ? (cl_mem*) alloca(mem_objects->size() * sizeof(cl_mem)) + : NULL; + + if (mems != NULL) { + for (unsigned int i = 0; i < mem_objects->size(); i++) { + mems[i] = ((*mem_objects)[i])(); + } + } + + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueNativeKernel( + object_, userFptr, args.first, args.second, + (mem_objects != NULL) ? (cl_uint) mem_objects->size() : 0, + mems, + (mem_locs != NULL && mem_locs->size() > 0) ? (const void **) &mem_locs->front() : NULL, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_NATIVE_KERNEL); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + +/** + * Deprecated APIs for 1.2 + */ +#if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) || (defined(CL_VERSION_1_1) && !defined(CL_VERSION_1_2)) + CL_EXT_PREFIX__VERSION_1_1_DEPRECATED + cl_int enqueueMarker(Event* event = NULL) const CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueMarker( + object_, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_MARKER_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + CL_EXT_PREFIX__VERSION_1_1_DEPRECATED + cl_int enqueueWaitForEvents(const VECTOR_CLASS& events) const CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED + { + return detail::errHandler( + ::clEnqueueWaitForEvents( + object_, + (cl_uint) events.size(), + events.size() > 0 ? (const cl_event*) &events.front() : NULL), + __ENQUEUE_WAIT_FOR_EVENTS_ERR); + } +#endif // #if defined(CL_VERSION_1_1) + + cl_int enqueueAcquireGLObjects( + const VECTOR_CLASS* mem_objects = NULL, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueAcquireGLObjects( + object_, + (mem_objects != NULL) ? (cl_uint) mem_objects->size() : 0, + (mem_objects != NULL && mem_objects->size() > 0) ? (const cl_mem *) &mem_objects->front(): NULL, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_ACQUIRE_GL_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + cl_int enqueueReleaseGLObjects( + const VECTOR_CLASS* mem_objects = NULL, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueReleaseGLObjects( + object_, + (mem_objects != NULL) ? (cl_uint) mem_objects->size() : 0, + (mem_objects != NULL && mem_objects->size() > 0) ? (const cl_mem *) &mem_objects->front(): NULL, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_RELEASE_GL_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + +#if defined (USE_DX_INTEROP) +typedef CL_API_ENTRY cl_int (CL_API_CALL *PFN_clEnqueueAcquireD3D10ObjectsKHR)( + cl_command_queue command_queue, cl_uint num_objects, + const cl_mem* mem_objects, cl_uint num_events_in_wait_list, + const cl_event* event_wait_list, cl_event* event); +typedef CL_API_ENTRY cl_int (CL_API_CALL *PFN_clEnqueueReleaseD3D10ObjectsKHR)( + cl_command_queue command_queue, cl_uint num_objects, + const cl_mem* mem_objects, cl_uint num_events_in_wait_list, + const cl_event* event_wait_list, cl_event* event); + + cl_int enqueueAcquireD3D10Objects( + const VECTOR_CLASS* mem_objects = NULL, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + static PFN_clEnqueueAcquireD3D10ObjectsKHR pfn_clEnqueueAcquireD3D10ObjectsKHR = NULL; +#if defined(CL_VERSION_1_2) + cl_context context = getInfo(); + cl::Device device(getInfo()); + cl_platform_id platform = device.getInfo(); + __INIT_CL_EXT_FCN_PTR_PLATFORM(platform, clEnqueueAcquireD3D10ObjectsKHR); +#endif +#if defined(CL_VERSION_1_1) + __INIT_CL_EXT_FCN_PTR(clEnqueueAcquireD3D10ObjectsKHR); +#endif + + cl_event tmp; + cl_int err = detail::errHandler( + pfn_clEnqueueAcquireD3D10ObjectsKHR( + object_, + (mem_objects != NULL) ? (cl_uint) mem_objects->size() : 0, + (mem_objects != NULL && mem_objects->size() > 0) ? (const cl_mem *) &mem_objects->front(): NULL, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_ACQUIRE_GL_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } + + cl_int enqueueReleaseD3D10Objects( + const VECTOR_CLASS* mem_objects = NULL, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) const + { + static PFN_clEnqueueReleaseD3D10ObjectsKHR pfn_clEnqueueReleaseD3D10ObjectsKHR = NULL; +#if defined(CL_VERSION_1_2) + cl_context context = getInfo(); + cl::Device device(getInfo()); + cl_platform_id platform = device.getInfo(); + __INIT_CL_EXT_FCN_PTR_PLATFORM(platform, clEnqueueReleaseD3D10ObjectsKHR); +#endif // #if defined(CL_VERSION_1_2) +#if defined(CL_VERSION_1_1) + __INIT_CL_EXT_FCN_PTR(clEnqueueReleaseD3D10ObjectsKHR); +#endif // #if defined(CL_VERSION_1_1) + + cl_event tmp; + cl_int err = detail::errHandler( + pfn_clEnqueueReleaseD3D10ObjectsKHR( + object_, + (mem_objects != NULL) ? (cl_uint) mem_objects->size() : 0, + (mem_objects != NULL && mem_objects->size() > 0) ? (const cl_mem *) &mem_objects->front(): NULL, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_RELEASE_GL_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; + } +#endif + +/** + * Deprecated APIs for 1.2 + */ +#if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) || (defined(CL_VERSION_1_1) && !defined(CL_VERSION_1_2)) + CL_EXT_PREFIX__VERSION_1_1_DEPRECATED + cl_int enqueueBarrier() const CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED + { + return detail::errHandler( + ::clEnqueueBarrier(object_), + __ENQUEUE_BARRIER_ERR); + } +#endif // #if defined(CL_VERSION_1_1) + + cl_int flush() const + { + return detail::errHandler(::clFlush(object_), __FLUSH_ERR); + } + + cl_int finish() const + { + return detail::errHandler(::clFinish(object_), __FINISH_ERR); + } +}; + +#ifdef _WIN32 +#ifdef CL_HPP_CPP11_ATOMICS_SUPPORTED +__declspec(selectany) std::atomic CommandQueue::default_initialized_; +#else // !CL_HPP_CPP11_ATOMICS_SUPPORTED +__declspec(selectany) volatile int CommandQueue::default_initialized_ = __DEFAULT_NOT_INITIALIZED; +#endif // !CL_HPP_CPP11_ATOMICS_SUPPORTED +__declspec(selectany) CommandQueue CommandQueue::default_; +__declspec(selectany) volatile cl_int CommandQueue::default_error_ = CL_SUCCESS; +#else // !_WIN32 +#ifdef CL_HPP_CPP11_ATOMICS_SUPPORTED +__attribute__((weak)) std::atomic CommandQueue::default_initialized_; +#else // !CL_HPP_CPP11_ATOMICS_SUPPORTED +__attribute__((weak)) volatile int CommandQueue::default_initialized_ = __DEFAULT_NOT_INITIALIZED; +#endif // !CL_HPP_CPP11_ATOMICS_SUPPORTED +__attribute__((weak)) CommandQueue CommandQueue::default_; +__attribute__((weak)) volatile cl_int CommandQueue::default_error_ = CL_SUCCESS; +#endif // !_WIN32 + +template< typename IteratorType > +Buffer::Buffer( + const Context &context, + IteratorType startIterator, + IteratorType endIterator, + bool readOnly, + bool useHostPtr, + cl_int* err) +{ + typedef typename std::iterator_traits::value_type DataType; + cl_int error; + + cl_mem_flags flags = 0; + if( readOnly ) { + flags |= CL_MEM_READ_ONLY; + } + else { + flags |= CL_MEM_READ_WRITE; + } + if( useHostPtr ) { + flags |= CL_MEM_USE_HOST_PTR; + } + + ::size_t size = sizeof(DataType)*(endIterator - startIterator); + + if( useHostPtr ) { + object_ = ::clCreateBuffer(context(), flags, size, static_cast(&*startIterator), &error); + } else { + object_ = ::clCreateBuffer(context(), flags, size, 0, &error); + } + + detail::errHandler(error, __CREATE_BUFFER_ERR); + if (err != NULL) { + *err = error; + } + + if( !useHostPtr ) { + CommandQueue queue(context, 0, &error); + detail::errHandler(error, __CREATE_BUFFER_ERR); + if (err != NULL) { + *err = error; + } + + error = cl::copy(queue, startIterator, endIterator, *this); + detail::errHandler(error, __CREATE_BUFFER_ERR); + if (err != NULL) { + *err = error; + } + } +} + +template< typename IteratorType > +Buffer::Buffer( + const CommandQueue &queue, + IteratorType startIterator, + IteratorType endIterator, + bool readOnly, + bool useHostPtr, + cl_int* err) +{ + typedef typename std::iterator_traits::value_type DataType; + cl_int error; + + cl_mem_flags flags = 0; + if (readOnly) { + flags |= CL_MEM_READ_ONLY; + } + else { + flags |= CL_MEM_READ_WRITE; + } + if (useHostPtr) { + flags |= CL_MEM_USE_HOST_PTR; + } + + ::size_t size = sizeof(DataType)*(endIterator - startIterator); + + Context context = queue.getInfo(); + + if (useHostPtr) { + object_ = ::clCreateBuffer(context(), flags, size, static_cast(&*startIterator), &error); + } + else { + object_ = ::clCreateBuffer(context(), flags, size, 0, &error); + } + + detail::errHandler(error, __CREATE_BUFFER_ERR); + if (err != NULL) { + *err = error; + } + + if (!useHostPtr) { + error = cl::copy(queue, startIterator, endIterator, *this); + detail::errHandler(error, __CREATE_BUFFER_ERR); + if (err != NULL) { + *err = error; + } + } +} + +inline cl_int enqueueReadBuffer( + const Buffer& buffer, + cl_bool blocking, + ::size_t offset, + ::size_t size, + void* ptr, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if (error != CL_SUCCESS) { + return error; + } + + return queue.enqueueReadBuffer(buffer, blocking, offset, size, ptr, events, event); +} + +inline cl_int enqueueWriteBuffer( + const Buffer& buffer, + cl_bool blocking, + ::size_t offset, + ::size_t size, + const void* ptr, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if (error != CL_SUCCESS) { + return error; + } + + return queue.enqueueWriteBuffer(buffer, blocking, offset, size, ptr, events, event); +} + +inline void* enqueueMapBuffer( + const Buffer& buffer, + cl_bool blocking, + cl_map_flags flags, + ::size_t offset, + ::size_t size, + const VECTOR_CLASS* events = NULL, + Event* event = NULL, + cl_int* err = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + detail::errHandler(error, __ENQUEUE_MAP_BUFFER_ERR); + if (err != NULL) { + *err = error; + } + + void * result = ::clEnqueueMapBuffer( + queue(), buffer(), blocking, flags, offset, size, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (cl_event*) event, + &error); + + detail::errHandler(error, __ENQUEUE_MAP_BUFFER_ERR); + if (err != NULL) { + *err = error; + } + return result; +} + +inline cl_int enqueueUnmapMemObject( + const Memory& memory, + void* mapped_ptr, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + detail::errHandler(error, __ENQUEUE_MAP_BUFFER_ERR); + if (error != CL_SUCCESS) { + return error; + } + + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueUnmapMemObject( + queue(), memory(), mapped_ptr, + (events != NULL) ? (cl_uint) events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*) &events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_UNMAP_MEM_OBJECT_ERR); + + if (event != NULL && err == CL_SUCCESS) + *event = tmp; + + return err; +} + +inline cl_int enqueueCopyBuffer( + const Buffer& src, + const Buffer& dst, + ::size_t src_offset, + ::size_t dst_offset, + ::size_t size, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if (error != CL_SUCCESS) { + return error; + } + + return queue.enqueueCopyBuffer(src, dst, src_offset, dst_offset, size, events, event); +} + +/** + * Blocking copy operation between iterators and a buffer. + * Host to Device. + * Uses default command queue. + */ +template< typename IteratorType > +inline cl_int copy( IteratorType startIterator, IteratorType endIterator, cl::Buffer &buffer ) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + if (error != CL_SUCCESS) + return error; + + return cl::copy(queue, startIterator, endIterator, buffer); +} + +/** + * Blocking copy operation between iterators and a buffer. + * Device to Host. + * Uses default command queue. + */ +template< typename IteratorType > +inline cl_int copy( const cl::Buffer &buffer, IteratorType startIterator, IteratorType endIterator ) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + if (error != CL_SUCCESS) + return error; + + return cl::copy(queue, buffer, startIterator, endIterator); +} + +/** + * Blocking copy operation between iterators and a buffer. + * Host to Device. + * Uses specified queue. + */ +template< typename IteratorType > +inline cl_int copy( const CommandQueue &queue, IteratorType startIterator, IteratorType endIterator, cl::Buffer &buffer ) +{ + typedef typename std::iterator_traits::value_type DataType; + cl_int error; + + ::size_t length = endIterator-startIterator; + ::size_t byteLength = length*sizeof(DataType); + + DataType *pointer = + static_cast(queue.enqueueMapBuffer(buffer, CL_TRUE, CL_MAP_WRITE, 0, byteLength, 0, 0, &error)); + // if exceptions enabled, enqueueMapBuffer will throw + if( error != CL_SUCCESS ) { + return error; + } +#if defined(_MSC_VER) + std::copy( + startIterator, + endIterator, + stdext::checked_array_iterator( + pointer, length)); +#else + std::copy(startIterator, endIterator, pointer); +#endif + Event endEvent; + error = queue.enqueueUnmapMemObject(buffer, pointer, 0, &endEvent); + // if exceptions enabled, enqueueUnmapMemObject will throw + if( error != CL_SUCCESS ) { + return error; + } + endEvent.wait(); + return CL_SUCCESS; +} + +/** + * Blocking copy operation between iterators and a buffer. + * Device to Host. + * Uses specified queue. + */ +template< typename IteratorType > +inline cl_int copy( const CommandQueue &queue, const cl::Buffer &buffer, IteratorType startIterator, IteratorType endIterator ) +{ + typedef typename std::iterator_traits::value_type DataType; + cl_int error; + + ::size_t length = endIterator-startIterator; + ::size_t byteLength = length*sizeof(DataType); + + DataType *pointer = + static_cast(queue.enqueueMapBuffer(buffer, CL_TRUE, CL_MAP_READ, 0, byteLength, 0, 0, &error)); + // if exceptions enabled, enqueueMapBuffer will throw + if( error != CL_SUCCESS ) { + return error; + } + std::copy(pointer, pointer + length, startIterator); + Event endEvent; + error = queue.enqueueUnmapMemObject(buffer, pointer, 0, &endEvent); + // if exceptions enabled, enqueueUnmapMemObject will throw + if( error != CL_SUCCESS ) { + return error; + } + endEvent.wait(); + return CL_SUCCESS; +} + +#if defined(CL_VERSION_1_1) +inline cl_int enqueueReadBufferRect( + const Buffer& buffer, + cl_bool blocking, + const size_t<3>& buffer_offset, + const size_t<3>& host_offset, + const size_t<3>& region, + ::size_t buffer_row_pitch, + ::size_t buffer_slice_pitch, + ::size_t host_row_pitch, + ::size_t host_slice_pitch, + void *ptr, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if (error != CL_SUCCESS) { + return error; + } + + return queue.enqueueReadBufferRect( + buffer, + blocking, + buffer_offset, + host_offset, + region, + buffer_row_pitch, + buffer_slice_pitch, + host_row_pitch, + host_slice_pitch, + ptr, + events, + event); +} + +inline cl_int enqueueWriteBufferRect( + const Buffer& buffer, + cl_bool blocking, + const size_t<3>& buffer_offset, + const size_t<3>& host_offset, + const size_t<3>& region, + ::size_t buffer_row_pitch, + ::size_t buffer_slice_pitch, + ::size_t host_row_pitch, + ::size_t host_slice_pitch, + void *ptr, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if (error != CL_SUCCESS) { + return error; + } + + return queue.enqueueWriteBufferRect( + buffer, + blocking, + buffer_offset, + host_offset, + region, + buffer_row_pitch, + buffer_slice_pitch, + host_row_pitch, + host_slice_pitch, + ptr, + events, + event); +} + +inline cl_int enqueueCopyBufferRect( + const Buffer& src, + const Buffer& dst, + const size_t<3>& src_origin, + const size_t<3>& dst_origin, + const size_t<3>& region, + ::size_t src_row_pitch, + ::size_t src_slice_pitch, + ::size_t dst_row_pitch, + ::size_t dst_slice_pitch, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if (error != CL_SUCCESS) { + return error; + } + + return queue.enqueueCopyBufferRect( + src, + dst, + src_origin, + dst_origin, + region, + src_row_pitch, + src_slice_pitch, + dst_row_pitch, + dst_slice_pitch, + events, + event); +} +#endif + +inline cl_int enqueueReadImage( + const Image& image, + cl_bool blocking, + const size_t<3>& origin, + const size_t<3>& region, + ::size_t row_pitch, + ::size_t slice_pitch, + void* ptr, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if (error != CL_SUCCESS) { + return error; + } + + return queue.enqueueReadImage( + image, + blocking, + origin, + region, + row_pitch, + slice_pitch, + ptr, + events, + event); +} + +inline cl_int enqueueWriteImage( + const Image& image, + cl_bool blocking, + const size_t<3>& origin, + const size_t<3>& region, + ::size_t row_pitch, + ::size_t slice_pitch, + void* ptr, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if (error != CL_SUCCESS) { + return error; + } + + return queue.enqueueWriteImage( + image, + blocking, + origin, + region, + row_pitch, + slice_pitch, + ptr, + events, + event); +} + +inline cl_int enqueueCopyImage( + const Image& src, + const Image& dst, + const size_t<3>& src_origin, + const size_t<3>& dst_origin, + const size_t<3>& region, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if (error != CL_SUCCESS) { + return error; + } + + return queue.enqueueCopyImage( + src, + dst, + src_origin, + dst_origin, + region, + events, + event); +} + +inline cl_int enqueueCopyImageToBuffer( + const Image& src, + const Buffer& dst, + const size_t<3>& src_origin, + const size_t<3>& region, + ::size_t dst_offset, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if (error != CL_SUCCESS) { + return error; + } + + return queue.enqueueCopyImageToBuffer( + src, + dst, + src_origin, + region, + dst_offset, + events, + event); +} + +inline cl_int enqueueCopyBufferToImage( + const Buffer& src, + const Image& dst, + ::size_t src_offset, + const size_t<3>& dst_origin, + const size_t<3>& region, + const VECTOR_CLASS* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if (error != CL_SUCCESS) { + return error; + } + + return queue.enqueueCopyBufferToImage( + src, + dst, + src_offset, + dst_origin, + region, + events, + event); +} + + +inline cl_int flush(void) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if (error != CL_SUCCESS) { + return error; + } + + return queue.flush(); +} + +inline cl_int finish(void) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if (error != CL_SUCCESS) { + return error; + } + + + return queue.finish(); +} + +// Kernel Functor support +// New interface as of September 2011 +// Requires the C++11 std::tr1::function (note do not support TR1) +// Visual Studio 2010 and GCC 4.2 + +struct EnqueueArgs +{ + CommandQueue queue_; + const NDRange offset_; + const NDRange global_; + const NDRange local_; + VECTOR_CLASS events_; + + EnqueueArgs(NDRange global) : + queue_(CommandQueue::getDefault()), + offset_(NullRange), + global_(global), + local_(NullRange) + { + + } + + EnqueueArgs(NDRange global, NDRange local) : + queue_(CommandQueue::getDefault()), + offset_(NullRange), + global_(global), + local_(local) + { + + } + + EnqueueArgs(NDRange offset, NDRange global, NDRange local) : + queue_(CommandQueue::getDefault()), + offset_(offset), + global_(global), + local_(local) + { + + } + + EnqueueArgs(Event e, NDRange global) : + queue_(CommandQueue::getDefault()), + offset_(NullRange), + global_(global), + local_(NullRange) + { + events_.push_back(e); + } + + EnqueueArgs(Event e, NDRange global, NDRange local) : + queue_(CommandQueue::getDefault()), + offset_(NullRange), + global_(global), + local_(local) + { + events_.push_back(e); + } + + EnqueueArgs(Event e, NDRange offset, NDRange global, NDRange local) : + queue_(CommandQueue::getDefault()), + offset_(offset), + global_(global), + local_(local) + { + events_.push_back(e); + } + + EnqueueArgs(const VECTOR_CLASS &events, NDRange global) : + queue_(CommandQueue::getDefault()), + offset_(NullRange), + global_(global), + local_(NullRange), + events_(events) + { + + } + + EnqueueArgs(const VECTOR_CLASS &events, NDRange global, NDRange local) : + queue_(CommandQueue::getDefault()), + offset_(NullRange), + global_(global), + local_(local), + events_(events) + { + + } + + EnqueueArgs(const VECTOR_CLASS &events, NDRange offset, NDRange global, NDRange local) : + queue_(CommandQueue::getDefault()), + offset_(offset), + global_(global), + local_(local), + events_(events) + { + + } + + EnqueueArgs(CommandQueue &queue, NDRange global) : + queue_(queue), + offset_(NullRange), + global_(global), + local_(NullRange) + { + + } + + EnqueueArgs(CommandQueue &queue, NDRange global, NDRange local) : + queue_(queue), + offset_(NullRange), + global_(global), + local_(local) + { + + } + + EnqueueArgs(CommandQueue &queue, NDRange offset, NDRange global, NDRange local) : + queue_(queue), + offset_(offset), + global_(global), + local_(local) + { + + } + + EnqueueArgs(CommandQueue &queue, Event e, NDRange global) : + queue_(queue), + offset_(NullRange), + global_(global), + local_(NullRange) + { + events_.push_back(e); + } + + EnqueueArgs(CommandQueue &queue, Event e, NDRange global, NDRange local) : + queue_(queue), + offset_(NullRange), + global_(global), + local_(local) + { + events_.push_back(e); + } + + EnqueueArgs(CommandQueue &queue, Event e, NDRange offset, NDRange global, NDRange local) : + queue_(queue), + offset_(offset), + global_(global), + local_(local) + { + events_.push_back(e); + } + + EnqueueArgs(CommandQueue &queue, const VECTOR_CLASS &events, NDRange global) : + queue_(queue), + offset_(NullRange), + global_(global), + local_(NullRange), + events_(events) + { + + } + + EnqueueArgs(CommandQueue &queue, const VECTOR_CLASS &events, NDRange global, NDRange local) : + queue_(queue), + offset_(NullRange), + global_(global), + local_(local), + events_(events) + { + + } + + EnqueueArgs(CommandQueue &queue, const VECTOR_CLASS &events, NDRange offset, NDRange global, NDRange local) : + queue_(queue), + offset_(offset), + global_(global), + local_(local), + events_(events) + { + + } +}; + +namespace detail { + +class NullType {}; + +template +struct SetArg +{ + static void set (Kernel kernel, T0 arg) + { + kernel.setArg(index, arg); + } +}; + +template +struct SetArg +{ + static void set (Kernel, NullType) + { + } +}; + +template < + typename T0, typename T1, typename T2, typename T3, + typename T4, typename T5, typename T6, typename T7, + typename T8, typename T9, typename T10, typename T11, + typename T12, typename T13, typename T14, typename T15, + typename T16, typename T17, typename T18, typename T19, + typename T20, typename T21, typename T22, typename T23, + typename T24, typename T25, typename T26, typename T27, + typename T28, typename T29, typename T30, typename T31 +> +class KernelFunctorGlobal +{ +private: + Kernel kernel_; + +public: + KernelFunctorGlobal( + Kernel kernel) : + kernel_(kernel) + {} + + KernelFunctorGlobal( + const Program& program, + const STRING_CLASS name, + cl_int * err = NULL) : + kernel_(program, name.c_str(), err) + {} + + Event operator() ( + const EnqueueArgs& args, + T0 t0, + T1 t1 = NullType(), + T2 t2 = NullType(), + T3 t3 = NullType(), + T4 t4 = NullType(), + T5 t5 = NullType(), + T6 t6 = NullType(), + T7 t7 = NullType(), + T8 t8 = NullType(), + T9 t9 = NullType(), + T10 t10 = NullType(), + T11 t11 = NullType(), + T12 t12 = NullType(), + T13 t13 = NullType(), + T14 t14 = NullType(), + T15 t15 = NullType(), + T16 t16 = NullType(), + T17 t17 = NullType(), + T18 t18 = NullType(), + T19 t19 = NullType(), + T20 t20 = NullType(), + T21 t21 = NullType(), + T22 t22 = NullType(), + T23 t23 = NullType(), + T24 t24 = NullType(), + T25 t25 = NullType(), + T26 t26 = NullType(), + T27 t27 = NullType(), + T28 t28 = NullType(), + T29 t29 = NullType(), + T30 t30 = NullType(), + T31 t31 = NullType() + ) + { + Event event; + SetArg<0, T0>::set(kernel_, t0); + SetArg<1, T1>::set(kernel_, t1); + SetArg<2, T2>::set(kernel_, t2); + SetArg<3, T3>::set(kernel_, t3); + SetArg<4, T4>::set(kernel_, t4); + SetArg<5, T5>::set(kernel_, t5); + SetArg<6, T6>::set(kernel_, t6); + SetArg<7, T7>::set(kernel_, t7); + SetArg<8, T8>::set(kernel_, t8); + SetArg<9, T9>::set(kernel_, t9); + SetArg<10, T10>::set(kernel_, t10); + SetArg<11, T11>::set(kernel_, t11); + SetArg<12, T12>::set(kernel_, t12); + SetArg<13, T13>::set(kernel_, t13); + SetArg<14, T14>::set(kernel_, t14); + SetArg<15, T15>::set(kernel_, t15); + SetArg<16, T16>::set(kernel_, t16); + SetArg<17, T17>::set(kernel_, t17); + SetArg<18, T18>::set(kernel_, t18); + SetArg<19, T19>::set(kernel_, t19); + SetArg<20, T20>::set(kernel_, t20); + SetArg<21, T21>::set(kernel_, t21); + SetArg<22, T22>::set(kernel_, t22); + SetArg<23, T23>::set(kernel_, t23); + SetArg<24, T24>::set(kernel_, t24); + SetArg<25, T25>::set(kernel_, t25); + SetArg<26, T26>::set(kernel_, t26); + SetArg<27, T27>::set(kernel_, t27); + SetArg<28, T28>::set(kernel_, t28); + SetArg<29, T29>::set(kernel_, t29); + SetArg<30, T30>::set(kernel_, t30); + SetArg<31, T31>::set(kernel_, t31); + + args.queue_.enqueueNDRangeKernel( + kernel_, + args.offset_, + args.global_, + args.local_, + &args.events_, + &event); + + return event; + } + +}; + +//------------------------------------------------------------------------------------------------------ + + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16, + typename T17, + typename T18, + typename T19, + typename T20, + typename T21, + typename T22, + typename T23, + typename T24, + typename T25, + typename T26, + typename T27, + typename T28, + typename T29, + typename T30, + typename T31> +struct functionImplementation_ +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + T27, + T28, + T29, + T30, + T31> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 32)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + T27, + T28, + T29, + T30, + T31); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16, + T17 arg17, + T18 arg18, + T19 arg19, + T20 arg20, + T21 arg21, + T22 arg22, + T23 arg23, + T24 arg24, + T25 arg25, + T26 arg26, + T27 arg27, + T28 arg28, + T29 arg29, + T30 arg30, + T31 arg31) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16, + arg17, + arg18, + arg19, + arg20, + arg21, + arg22, + arg23, + arg24, + arg25, + arg26, + arg27, + arg28, + arg29, + arg30, + arg31); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16, + typename T17, + typename T18, + typename T19, + typename T20, + typename T21, + typename T22, + typename T23, + typename T24, + typename T25, + typename T26, + typename T27, + typename T28, + typename T29, + typename T30> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + T27, + T28, + T29, + T30, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + T27, + T28, + T29, + T30, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 31)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + T27, + T28, + T29, + T30); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16, + T17 arg17, + T18 arg18, + T19 arg19, + T20 arg20, + T21 arg21, + T22 arg22, + T23 arg23, + T24 arg24, + T25 arg25, + T26 arg26, + T27 arg27, + T28 arg28, + T29 arg29, + T30 arg30) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16, + arg17, + arg18, + arg19, + arg20, + arg21, + arg22, + arg23, + arg24, + arg25, + arg26, + arg27, + arg28, + arg29, + arg30); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16, + typename T17, + typename T18, + typename T19, + typename T20, + typename T21, + typename T22, + typename T23, + typename T24, + typename T25, + typename T26, + typename T27, + typename T28, + typename T29> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + T27, + T28, + T29, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + T27, + T28, + T29, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 30)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + T27, + T28, + T29); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16, + T17 arg17, + T18 arg18, + T19 arg19, + T20 arg20, + T21 arg21, + T22 arg22, + T23 arg23, + T24 arg24, + T25 arg25, + T26 arg26, + T27 arg27, + T28 arg28, + T29 arg29) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16, + arg17, + arg18, + arg19, + arg20, + arg21, + arg22, + arg23, + arg24, + arg25, + arg26, + arg27, + arg28, + arg29); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16, + typename T17, + typename T18, + typename T19, + typename T20, + typename T21, + typename T22, + typename T23, + typename T24, + typename T25, + typename T26, + typename T27, + typename T28> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + T27, + T28, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + T27, + T28, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 29)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + T27, + T28); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16, + T17 arg17, + T18 arg18, + T19 arg19, + T20 arg20, + T21 arg21, + T22 arg22, + T23 arg23, + T24 arg24, + T25 arg25, + T26 arg26, + T27 arg27, + T28 arg28) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16, + arg17, + arg18, + arg19, + arg20, + arg21, + arg22, + arg23, + arg24, + arg25, + arg26, + arg27, + arg28); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16, + typename T17, + typename T18, + typename T19, + typename T20, + typename T21, + typename T22, + typename T23, + typename T24, + typename T25, + typename T26, + typename T27> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + T27, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + T27, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 28)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + T27); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16, + T17 arg17, + T18 arg18, + T19 arg19, + T20 arg20, + T21 arg21, + T22 arg22, + T23 arg23, + T24 arg24, + T25 arg25, + T26 arg26, + T27 arg27) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16, + arg17, + arg18, + arg19, + arg20, + arg21, + arg22, + arg23, + arg24, + arg25, + arg26, + arg27); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16, + typename T17, + typename T18, + typename T19, + typename T20, + typename T21, + typename T22, + typename T23, + typename T24, + typename T25, + typename T26> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 27)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + T26); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16, + T17 arg17, + T18 arg18, + T19 arg19, + T20 arg20, + T21 arg21, + T22 arg22, + T23 arg23, + T24 arg24, + T25 arg25, + T26 arg26) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16, + arg17, + arg18, + arg19, + arg20, + arg21, + arg22, + arg23, + arg24, + arg25, + arg26); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16, + typename T17, + typename T18, + typename T19, + typename T20, + typename T21, + typename T22, + typename T23, + typename T24, + typename T25> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 26)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + T25); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16, + T17 arg17, + T18 arg18, + T19 arg19, + T20 arg20, + T21 arg21, + T22 arg22, + T23 arg23, + T24 arg24, + T25 arg25) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16, + arg17, + arg18, + arg19, + arg20, + arg21, + arg22, + arg23, + arg24, + arg25); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16, + typename T17, + typename T18, + typename T19, + typename T20, + typename T21, + typename T22, + typename T23, + typename T24> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 25)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + T24); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16, + T17 arg17, + T18 arg18, + T19 arg19, + T20 arg20, + T21 arg21, + T22 arg22, + T23 arg23, + T24 arg24) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16, + arg17, + arg18, + arg19, + arg20, + arg21, + arg22, + arg23, + arg24); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16, + typename T17, + typename T18, + typename T19, + typename T20, + typename T21, + typename T22, + typename T23> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 24)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + T23); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16, + T17 arg17, + T18 arg18, + T19 arg19, + T20 arg20, + T21 arg21, + T22 arg22, + T23 arg23) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16, + arg17, + arg18, + arg19, + arg20, + arg21, + arg22, + arg23); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16, + typename T17, + typename T18, + typename T19, + typename T20, + typename T21, + typename T22> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 23)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + T22); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16, + T17 arg17, + T18 arg18, + T19 arg19, + T20 arg20, + T21 arg21, + T22 arg22) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16, + arg17, + arg18, + arg19, + arg20, + arg21, + arg22); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16, + typename T17, + typename T18, + typename T19, + typename T20, + typename T21> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 22)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + T21); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16, + T17 arg17, + T18 arg18, + T19 arg19, + T20 arg20, + T21 arg21) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16, + arg17, + arg18, + arg19, + arg20, + arg21); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16, + typename T17, + typename T18, + typename T19, + typename T20> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 21)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + T20); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16, + T17 arg17, + T18 arg18, + T19 arg19, + T20 arg20) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16, + arg17, + arg18, + arg19, + arg20); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16, + typename T17, + typename T18, + typename T19> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 20)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + T19); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16, + T17 arg17, + T18 arg18, + T19 arg19) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16, + arg17, + arg18, + arg19); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16, + typename T17, + typename T18> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 19)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + T18); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16, + T17 arg17, + T18 arg18) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16, + arg17, + arg18); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16, + typename T17> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 18)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + T17); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16, + T17 arg17) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16, + arg17); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15, + typename T16> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 17)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + T16); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15, + T16 arg16) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15, + arg16); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14, + typename T15> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 16)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + T15); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14, + T15 arg15) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14, + arg15); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13, + typename T14> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 15)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + T14); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13, + T14 arg14) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13, + arg14); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12, + typename T13> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 14)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + T13); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12, + T13 arg13) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12, + arg13); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11, + typename T12> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 13)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + T12); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11, + T12 arg12) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11, + arg12); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10, + typename T11> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 12)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + T11); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10, + T11 arg11) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10, + arg11); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9, + typename T10> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 11)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + T10); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9, + T10 arg10) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9, + arg10); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 10)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + T9); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8, + T9 arg9) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8, + arg9); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 9)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7, + T8 arg8) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7, + arg8); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 8)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6, + T7); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6, + T7 arg7) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6, + arg7); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + T6, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + T6, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 7)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5, + T6); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5, + T6 arg6) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5, + arg6); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + T5, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + T5, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 6)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4, + T5); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4, + T5 arg5) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4, + arg5); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + T4, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + T4, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 5)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3, + T4); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3, + T4 arg4) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3, + arg4); + } + + +}; + +template< + typename T0, + typename T1, + typename T2, + typename T3> +struct functionImplementation_ +< T0, + T1, + T2, + T3, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + T3, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 4)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2, + T3); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2, + T3 arg3) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2, + arg3); + } + + +}; + +template< + typename T0, + typename T1, + typename T2> +struct functionImplementation_ +< T0, + T1, + T2, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + T2, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 3)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1, + T2); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1, + T2 arg2) + { + return functor_( + enqueueArgs, + arg0, + arg1, + arg2); + } + + +}; + +template< + typename T0, + typename T1> +struct functionImplementation_ +< T0, + T1, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + T1, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 2)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0, + T1); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0, + T1 arg1) + { + return functor_( + enqueueArgs, + arg0, + arg1); + } + + +}; + +template< + typename T0> +struct functionImplementation_ +< T0, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> +{ + typedef detail::KernelFunctorGlobal< + T0, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType, + NullType> FunctorType; + + FunctorType functor_; + + functionImplementation_(const FunctorType &functor) : + functor_(functor) + { + + #if (defined(_WIN32) && defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 1)) + // Fail variadic expansion for dev11 + static_assert(0, "Visual Studio has a hard limit of argument count for a std::function expansion. Please define _VARIADIC_MAX to be 10. If you need more arguments than that VC12 and below cannot support it."); + #endif + + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + T0); + + Event operator()( + const EnqueueArgs& enqueueArgs, + T0 arg0) + { + return functor_( + enqueueArgs, + arg0); + } + + +}; + + + + + +} // namespace detail + +//---------------------------------------------------------------------------------------------- + +template < + typename T0, typename T1 = detail::NullType, typename T2 = detail::NullType, + typename T3 = detail::NullType, typename T4 = detail::NullType, + typename T5 = detail::NullType, typename T6 = detail::NullType, + typename T7 = detail::NullType, typename T8 = detail::NullType, + typename T9 = detail::NullType, typename T10 = detail::NullType, + typename T11 = detail::NullType, typename T12 = detail::NullType, + typename T13 = detail::NullType, typename T14 = detail::NullType, + typename T15 = detail::NullType, typename T16 = detail::NullType, + typename T17 = detail::NullType, typename T18 = detail::NullType, + typename T19 = detail::NullType, typename T20 = detail::NullType, + typename T21 = detail::NullType, typename T22 = detail::NullType, + typename T23 = detail::NullType, typename T24 = detail::NullType, + typename T25 = detail::NullType, typename T26 = detail::NullType, + typename T27 = detail::NullType, typename T28 = detail::NullType, + typename T29 = detail::NullType, typename T30 = detail::NullType, + typename T31 = detail::NullType +> +struct make_kernel : + public detail::functionImplementation_< + T0, T1, T2, T3, + T4, T5, T6, T7, + T8, T9, T10, T11, + T12, T13, T14, T15, + T16, T17, T18, T19, + T20, T21, T22, T23, + T24, T25, T26, T27, + T28, T29, T30, T31 + > +{ +public: + typedef detail::KernelFunctorGlobal< + T0, T1, T2, T3, + T4, T5, T6, T7, + T8, T9, T10, T11, + T12, T13, T14, T15, + T16, T17, T18, T19, + T20, T21, T22, T23, + T24, T25, T26, T27, + T28, T29, T30, T31 + > FunctorType; + + make_kernel( + const Program& program, + const STRING_CLASS name, + cl_int * err = NULL) : + detail::functionImplementation_< + T0, T1, T2, T3, + T4, T5, T6, T7, + T8, T9, T10, T11, + T12, T13, T14, T15, + T16, T17, T18, T19, + T20, T21, T22, T23, + T24, T25, T26, T27, + T28, T29, T30, T31 + >( + FunctorType(program, name, err)) + {} + + make_kernel( + const Kernel kernel) : + detail::functionImplementation_< + T0, T1, T2, T3, + T4, T5, T6, T7, + T8, T9, T10, T11, + T12, T13, T14, T15, + T16, T17, T18, T19, + T20, T21, T22, T23, + T24, T25, T26, T27, + T28, T29, T30, T31 + >( + FunctorType(kernel)) + {} +}; + + +//---------------------------------------------------------------------------------------------------------------------- + +#undef __ERR_STR +#if !defined(__CL_USER_OVERRIDE_ERROR_STRINGS) +#undef __GET_DEVICE_INFO_ERR +#undef __GET_PLATFORM_INFO_ERR +#undef __GET_DEVICE_IDS_ERR +#undef __GET_CONTEXT_INFO_ERR +#undef __GET_EVENT_INFO_ERR +#undef __GET_EVENT_PROFILE_INFO_ERR +#undef __GET_MEM_OBJECT_INFO_ERR +#undef __GET_IMAGE_INFO_ERR +#undef __GET_SAMPLER_INFO_ERR +#undef __GET_KERNEL_INFO_ERR +#undef __GET_KERNEL_ARG_INFO_ERR +#undef __GET_KERNEL_WORK_GROUP_INFO_ERR +#undef __GET_PROGRAM_INFO_ERR +#undef __GET_PROGRAM_BUILD_INFO_ERR +#undef __GET_COMMAND_QUEUE_INFO_ERR + +#undef __CREATE_CONTEXT_ERR +#undef __CREATE_CONTEXT_FROM_TYPE_ERR +#undef __GET_SUPPORTED_IMAGE_FORMATS_ERR + +#undef __CREATE_BUFFER_ERR +#undef __CREATE_SUBBUFFER_ERR +#undef __CREATE_IMAGE2D_ERR +#undef __CREATE_IMAGE3D_ERR +#undef __CREATE_SAMPLER_ERR +#undef __SET_MEM_OBJECT_DESTRUCTOR_CALLBACK_ERR + +#undef __CREATE_USER_EVENT_ERR +#undef __SET_USER_EVENT_STATUS_ERR +#undef __SET_EVENT_CALLBACK_ERR +#undef __SET_PRINTF_CALLBACK_ERR + +#undef __WAIT_FOR_EVENTS_ERR + +#undef __CREATE_KERNEL_ERR +#undef __SET_KERNEL_ARGS_ERR +#undef __CREATE_PROGRAM_WITH_SOURCE_ERR +#undef __CREATE_PROGRAM_WITH_BINARY_ERR +#undef __CREATE_PROGRAM_WITH_BUILT_IN_KERNELS_ERR +#undef __BUILD_PROGRAM_ERR +#undef __CREATE_KERNELS_IN_PROGRAM_ERR + +#undef __CREATE_COMMAND_QUEUE_ERR +#undef __SET_COMMAND_QUEUE_PROPERTY_ERR +#undef __ENQUEUE_READ_BUFFER_ERR +#undef __ENQUEUE_WRITE_BUFFER_ERR +#undef __ENQUEUE_READ_BUFFER_RECT_ERR +#undef __ENQUEUE_WRITE_BUFFER_RECT_ERR +#undef __ENQEUE_COPY_BUFFER_ERR +#undef __ENQEUE_COPY_BUFFER_RECT_ERR +#undef __ENQUEUE_READ_IMAGE_ERR +#undef __ENQUEUE_WRITE_IMAGE_ERR +#undef __ENQUEUE_COPY_IMAGE_ERR +#undef __ENQUEUE_COPY_IMAGE_TO_BUFFER_ERR +#undef __ENQUEUE_COPY_BUFFER_TO_IMAGE_ERR +#undef __ENQUEUE_MAP_BUFFER_ERR +#undef __ENQUEUE_MAP_IMAGE_ERR +#undef __ENQUEUE_UNMAP_MEM_OBJECT_ERR +#undef __ENQUEUE_NDRANGE_KERNEL_ERR +#undef __ENQUEUE_TASK_ERR +#undef __ENQUEUE_NATIVE_KERNEL + +#undef __CL_EXPLICIT_CONSTRUCTORS + +#undef __UNLOAD_COMPILER_ERR +#endif //__CL_USER_OVERRIDE_ERROR_STRINGS + +#undef __CL_FUNCTION_TYPE + +// Extensions +/** + * Deprecated APIs for 1.2 + */ +#if defined(CL_VERSION_1_1) +#undef __INIT_CL_EXT_FCN_PTR +#endif // #if defined(CL_VERSION_1_1) +#undef __CREATE_SUB_DEVICES + +#if defined(USE_CL_DEVICE_FISSION) +#undef __PARAM_NAME_DEVICE_FISSION +#endif // USE_CL_DEVICE_FISSION + +#undef __DEFAULT_NOT_INITIALIZED +#undef __DEFAULT_BEING_INITIALIZED +#undef __DEFAULT_INITIALIZED + +#undef CL_HPP_RVALUE_REFERENCES_SUPPORTED +#undef CL_HPP_NOEXCEPT + +} // namespace cl + +#endif // CL_HPP_ diff --git a/include/lib/CL/cl2.hpp b/include/lib/CL/cl2.hpp new file mode 100644 index 0000000..07e3613 --- /dev/null +++ b/include/lib/CL/cl2.hpp @@ -0,0 +1,10465 @@ +/******************************************************************************* + * Copyright (c) 2008-2016 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS + * KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS + * SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT + * https://www.khronos.org/registry/ + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + ******************************************************************************/ + +/*! \file + * + * \brief C++ bindings for OpenCL 1.0 (rev 48), OpenCL 1.1 (rev 33), + * OpenCL 1.2 (rev 15) and OpenCL 2.0 (rev 29) + * \author Lee Howes and Bruce Merry + * + * Derived from the OpenCL 1.x C++ bindings written by + * Benedict R. Gaster, Laurent Morichetti and Lee Howes + * With additions and fixes from: + * Brian Cole, March 3rd 2010 and April 2012 + * Matt Gruenke, April 2012. + * Bruce Merry, February 2013. + * Tom Deakin and Simon McIntosh-Smith, July 2013 + * James Price, 2015- + * + * \version 2.0.10 + * \date 2016-07-20 + * + * Optional extension support + * + * cl_ext_device_fission + * #define CL_HPP_USE_CL_DEVICE_FISSION + * cl_khr_d3d10_sharing + * #define CL_HPP_USE_DX_INTEROP + * cl_khr_sub_groups + * #define CL_HPP_USE_CL_SUB_GROUPS_KHR + * + * Doxygen documentation for this header is available here: + * + * http://khronosgroup.github.io/OpenCL-CLHPP/ + * + * The latest version of this header can be found on the GitHub releases page: + * + * https://github.com/KhronosGroup/OpenCL-CLHPP/releases + * + * Bugs and patches can be submitted to the GitHub repository: + * + * https://github.com/KhronosGroup/OpenCL-CLHPP + */ + +/*! \mainpage + * \section intro Introduction + * For many large applications C++ is the language of choice and so it seems + * reasonable to define C++ bindings for OpenCL. + * + * The interface is contained with a single C++ header file \em cl2.hpp and all + * definitions are contained within the namespace \em cl. There is no additional + * requirement to include \em cl.h and to use either the C++ or original C + * bindings; it is enough to simply include \em cl2.hpp. + * + * The bindings themselves are lightweight and correspond closely to the + * underlying C API. Using the C++ bindings introduces no additional execution + * overhead. + * + * There are numerous compatibility, portability and memory management + * fixes in the new header as well as additional OpenCL 2.0 features. + * As a result the header is not directly backward compatible and for this + * reason we release it as cl2.hpp rather than a new version of cl.hpp. + * + * + * \section compatibility Compatibility + * Due to the evolution of the underlying OpenCL API the 2.0 C++ bindings + * include an updated approach to defining supported feature versions + * and the range of valid underlying OpenCL runtime versions supported. + * + * The combination of preprocessor macros CL_HPP_TARGET_OPENCL_VERSION and + * CL_HPP_MINIMUM_OPENCL_VERSION control this range. These are three digit + * decimal values representing OpenCL runime versions. The default for + * the target is 200, representing OpenCL 2.0 and the minimum is also + * defined as 200. These settings would use 2.0 API calls only. + * If backward compatibility with a 1.2 runtime is required, the minimum + * version may be set to 120. + * + * Note that this is a compile-time setting, and so affects linking against + * a particular SDK version rather than the versioning of the loaded runtime. + * + * The earlier versions of the header included basic vector and string + * classes based loosely on STL versions. These were difficult to + * maintain and very rarely used. For the 2.0 header we now assume + * the presence of the standard library unless requested otherwise. + * We use std::array, std::vector, std::shared_ptr and std::string + * throughout to safely manage memory and reduce the chance of a + * recurrance of earlier memory management bugs. + * + * These classes are used through typedefs in the cl namespace: + * cl::array, cl::vector, cl::pointer and cl::string. + * In addition cl::allocate_pointer forwards to std::allocate_shared + * by default. + * In all cases these standard library classes can be replaced with + * custom interface-compatible versions using the CL_HPP_NO_STD_ARRAY, + * CL_HPP_NO_STD_VECTOR, CL_HPP_NO_STD_UNIQUE_PTR and + * CL_HPP_NO_STD_STRING macros. + * + * The OpenCL 1.x versions of the C++ bindings included a size_t wrapper + * class to interface with kernel enqueue. This caused unpleasant interactions + * with the standard size_t declaration and led to namespacing bugs. + * In the 2.0 version we have replaced this with a std::array-based interface. + * However, the old behaviour can be regained for backward compatibility + * using the CL_HPP_ENABLE_SIZE_T_COMPATIBILITY macro. + * + * Finally, the program construction interface used a clumsy vector-of-pairs + * design in the earlier versions. We have replaced that with a cleaner + * vector-of-vectors and vector-of-strings design. However, for backward + * compatibility old behaviour can be regained with the + * CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY macro. + * + * In OpenCL 2.0 OpenCL C is not entirely backward compatibility with + * earlier versions. As a result a flag must be passed to the OpenCL C + * compiled to request OpenCL 2.0 compilation of kernels with 1.2 as + * the default in the absence of the flag. + * In some cases the C++ bindings automatically compile code for ease. + * For those cases the compilation defaults to OpenCL C 2.0. + * If this is not wanted, the CL_HPP_CL_1_2_DEFAULT_BUILD macro may + * be specified to assume 1.2 compilation. + * If more fine-grained decisions on a per-kernel bases are required + * then explicit build operations that take the flag should be used. + * + * + * \section parameterization Parameters + * This header may be parameterized by a set of preprocessor macros. + * + * - CL_HPP_TARGET_OPENCL_VERSION + * + * Defines the target OpenCL runtime version to build the header + * against. Defaults to 200, representing OpenCL 2.0. + * + * - CL_HPP_NO_STD_STRING + * + * Do not use the standard library string class. cl::string is not + * defined and may be defined by the user before cl2.hpp is + * included. + * + * - CL_HPP_NO_STD_VECTOR + * + * Do not use the standard library vector class. cl::vector is not + * defined and may be defined by the user before cl2.hpp is + * included. + * + * - CL_HPP_NO_STD_ARRAY + * + * Do not use the standard library array class. cl::array is not + * defined and may be defined by the user before cl2.hpp is + * included. + * + * - CL_HPP_NO_STD_UNIQUE_PTR + * + * Do not use the standard library unique_ptr class. cl::pointer and + * the cl::allocate_pointer functions are not defined and may be + * defined by the user before cl2.hpp is included. + * + * - CL_HPP_ENABLE_DEVICE_FISSION + * + * Enables device fission for OpenCL 1.2 platforms. + * + * - CL_HPP_ENABLE_EXCEPTIONS + * + * Enable exceptions for use in the C++ bindings header. This is the + * preferred error handling mechanism but is not required. + * + * - CL_HPP_ENABLE_SIZE_T_COMPATIBILITY + * + * Backward compatibility option to support cl.hpp-style size_t + * class. Replaces the updated std::array derived version and + * removal of size_t from the namespace. Note that in this case the + * new size_t class is placed in the cl::compatibility namespace and + * thus requires an additional using declaration for direct backward + * compatibility. + * + * - CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY + * + * Enable older vector of pairs interface for construction of + * programs. + * + * - CL_HPP_CL_1_2_DEFAULT_BUILD + * + * Default to OpenCL C 1.2 compilation rather than OpenCL C 2.0 + * applies to use of cl::Program construction and other program + * build variants. + * + * + * \section example Example + * + * The following example shows a general use case for the C++ + * bindings, including support for the optional exception feature and + * also the supplied vector and string classes, see following sections for + * decriptions of these features. + * + * \code + #define CL_HPP_ENABLE_EXCEPTIONS + #define CL_HPP_TARGET_OPENCL_VERSION 200 + + #include + #include + #include + #include + #include + + const int numElements = 32; + + int main(void) + { + // Filter for a 2.0 platform and set it as the default + std::vector platforms; + cl::Platform::get(&platforms); + cl::Platform plat; + for (auto &p : platforms) { + std::string platver = p.getInfo(); + if (platver.find("OpenCL 2.") != std::string::npos) { + plat = p; + } + } + if (plat() == 0) { + std::cout << "No OpenCL 2.0 platform found."; + return -1; + } + + cl::Platform newP = cl::Platform::setDefault(plat); + if (newP != plat) { + std::cout << "Error setting default platform."; + return -1; + } + + // Use C++11 raw string literals for kernel source code + std::string kernel1{R"CLC( + global int globalA; + kernel void updateGlobal() + { + globalA = 75; + } + )CLC"}; + std::string kernel2{R"CLC( + typedef struct { global int *bar; } Foo; + kernel void vectorAdd(global const Foo* aNum, global const int *inputA, global const int + **inputB, + global int *output, int val, write_only pipe int outPipe, queue_t + *childQueue) + { + output[get_global_id(0)] = inputA[get_global_id(0)] + inputB[get_global_id(0)] + val + + **(aNum->bar); + write_pipe(outPipe, &val); + queue_t default_queue = get_default_queue(); + ndrange_t ndrange = ndrange_1D(get_global_size(0)/2, get_global_size(0)/2); + + // Have a child kernel write into third quarter of output + enqueue_kernel(default_queue, CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange, + ^{ + output[get_global_size(0)*2 + get_global_id(0)] = + inputA[get_global_size(0)*2 + get_global_id(0)] + inputB[get_global_size(0)*2 + *+ get_global_id(0)] + globalA; + }); + + // Have a child kernel write into last quarter of output + enqueue_kernel(childQueue, CLK_ENQUEUE_FLAGS_WAIT_KERNEL, ndrange, + ^{ + output[get_global_size(0)*3 + get_global_id(0)] = + inputA[get_global_size(0)*3 + get_global_id(0)] + inputB[get_global_size(0)*3 + *+ get_global_id(0)] + globalA + 2; + }); + } + )CLC"}; + + // New simpler string interface style + std::vector programStrings {kernel1, kernel2}; + + cl::Program vectorAddProgram(programStrings); + try { + vectorAddProgram.build("-cl-std=CL2.0"); + } + catch (...) { + // Print build info for all devices + cl_int buildErr = CL_SUCCESS; + auto buildInfo = vectorAddProgram.getBuildInfo(&buildErr); + for (auto &pair : buildInfo) { + std::cerr << pair.second << std::endl << std::endl; + } + + return 1; + } + + typedef struct { int *bar; } Foo; + + // Get and run kernel that initializes the program-scope global + // A test for kernels that take no arguments + auto program2Kernel = + cl::KernelFunctor<>(vectorAddProgram, "updateGlobal"); + program2Kernel( + cl::EnqueueArgs( + cl::NDRange(1))); + + ////////////////// + // SVM allocations + + auto anSVMInt = cl::allocate_svm>(); + * anSVMInt = 5; + cl::SVMAllocator>> svmAllocReadOnly; + auto fooPointer = cl::allocate_pointer(svmAllocReadOnly); + fooPointer->bar = anSVMInt.get(); + cl::SVMAllocator> svmAlloc; + std::vector>> inputA(numElements, 1, + *svmAlloc); + cl::coarse_svm_vector inputB(numElements, 2, svmAlloc); + + // + ////////////// + + // Traditional cl_mem allocations + std::vector output(numElements, 0xdeadbeef); + cl::Buffer outputBuffer(begin(output), end(output), false); + cl::Pipe aPipe(sizeof(cl_int), numElements / 2); + + // Default command queue, also passed in as a parameter + cl::DeviceCommandQueue defaultDeviceQueue = cl::DeviceCommandQueue::makeDefault( + cl::Context::getDefault(), cl::Device::getDefault()); + + auto vectorAddKernel = + cl::KernelFunctor< + decltype(fooPointer)&, + int*, + cl::coarse_svm_vector&, + cl::Buffer, + int, + cl::Pipe&, + cl::DeviceCommandQueue + >(vectorAddProgram, "vectorAdd"); + + // Ensure that the additional SVM pointer is available to the kernel + // This one was not passed as a parameter + vectorAddKernel.setSVMPointers(anSVMInt); + + // Hand control of coarse allocations to runtime + cl::enqueueUnmapSVM(anSVMInt); + cl::enqueueUnmapSVM(fooPointer); + cl::unmapSVM(inputB); + cl::unmapSVM(output2); + + cl_int error; + vectorAddKernel( + cl::EnqueueArgs( + cl::NDRange(numElements/2), + cl::NDRange(numElements/2)), + fooPointer, + inputA.data(), + inputB, + outputBuffer, + 3, + aPipe, + defaultDeviceQueue, + error + ); + + cl::copy(outputBuffer, begin(output), end(output)); + // Grab the SVM output vector using a map + cl::mapSVM(output2); + + cl::Device d = cl::Device::getDefault(); + + std::cout << "Output:\n"; + for (int i = 1; i < numElements; ++i) { + std::cout << "\t" << output[i] << "\n"; + } + std::cout << "\n\n"; + + return 0; + } + * + * \endcode + * + */ +#ifndef CL_HPP_ +#define CL_HPP_ + +/* Handle deprecated preprocessor definitions. In each case, we only check for + * the old name if the new name is not defined, so that user code can define + * both and hence work with either version of the bindings. + */ +#if !defined(CL_HPP_USE_DX_INTEROP) && defined(USE_DX_INTEROP) +# pragma message("cl2.hpp: USE_DX_INTEROP is deprecated. Define CL_HPP_USE_DX_INTEROP instead") +# define CL_HPP_USE_DX_INTEROP +#endif +#if !defined(CL_HPP_USE_CL_DEVICE_FISSION) && defined(USE_CL_DEVICE_FISSION) +# pragma \ + message("cl2.hpp: USE_CL_DEVICE_FISSION is deprecated. Define CL_HPP_USE_CL_DEVICE_FISSION instead") +# define CL_HPP_USE_CL_DEVICE_FISSION +#endif +#if !defined(CL_HPP_ENABLE_EXCEPTIONS) && defined(__CL_ENABLE_EXCEPTIONS) +# pragma \ + message("cl2.hpp: __CL_ENABLE_EXCEPTIONS is deprecated. Define CL_HPP_ENABLE_EXCEPTIONS instead") +# define CL_HPP_ENABLE_EXCEPTIONS +#endif +#if !defined(CL_HPP_NO_STD_VECTOR) && defined(__NO_STD_VECTOR) +# pragma message("cl2.hpp: __NO_STD_VECTOR is deprecated. Define CL_HPP_NO_STD_VECTOR instead") +# define CL_HPP_NO_STD_VECTOR +#endif +#if !defined(CL_HPP_NO_STD_STRING) && defined(__NO_STD_STRING) +# pragma message("cl2.hpp: __NO_STD_STRING is deprecated. Define CL_HPP_NO_STD_STRING instead") +# define CL_HPP_NO_STD_STRING +#endif +#if defined(VECTOR_CLASS) +# pragma message("cl2.hpp: VECTOR_CLASS is deprecated. Alias cl::vector instead") +#endif +#if defined(STRING_CLASS) +# pragma message("cl2.hpp: STRING_CLASS is deprecated. Alias cl::string instead.") +#endif +#if !defined(CL_HPP_USER_OVERRIDE_ERROR_STRINGS) && defined(__CL_USER_OVERRIDE_ERROR_STRINGS) +# pragma \ + message("cl2.hpp: __CL_USER_OVERRIDE_ERROR_STRINGS is deprecated. Define CL_HPP_USER_OVERRIDE_ERROR_STRINGS instead") +# define CL_HPP_USER_OVERRIDE_ERROR_STRINGS +#endif + +/* Warn about features that are no longer supported + */ +#if defined(__USE_DEV_VECTOR) +# pragma message("cl2.hpp: __USE_DEV_VECTOR is no longer supported. Expect compilation errors") +#endif +#if defined(__USE_DEV_STRING) +# pragma message("cl2.hpp: __USE_DEV_STRING is no longer supported. Expect compilation errors") +#endif + +/* Detect which version to target */ +#if !defined(CL_HPP_TARGET_OPENCL_VERSION) +# pragma \ + message("cl2.hpp: CL_HPP_TARGET_OPENCL_VERSION is not defined. It will default to 200 (OpenCL 2.0)") +# define CL_HPP_TARGET_OPENCL_VERSION 200 +#endif +#if CL_HPP_TARGET_OPENCL_VERSION != 100 && CL_HPP_TARGET_OPENCL_VERSION != 110 && \ + CL_HPP_TARGET_OPENCL_VERSION != 120 && CL_HPP_TARGET_OPENCL_VERSION != 200 +# pragma \ + message("cl2.hpp: CL_HPP_TARGET_OPENCL_VERSION is not a valid value (100, 110, 120 or 200). It will be set to 200") +# undef CL_HPP_TARGET_OPENCL_VERSION +# define CL_HPP_TARGET_OPENCL_VERSION 200 +#endif + +#if !defined(CL_HPP_MINIMUM_OPENCL_VERSION) +# define CL_HPP_MINIMUM_OPENCL_VERSION 200 +#endif +#if CL_HPP_MINIMUM_OPENCL_VERSION != 100 && CL_HPP_MINIMUM_OPENCL_VERSION != 110 && \ + CL_HPP_MINIMUM_OPENCL_VERSION != 120 && CL_HPP_MINIMUM_OPENCL_VERSION != 200 +# pragma \ + message("cl2.hpp: CL_HPP_MINIMUM_OPENCL_VERSION is not a valid value (100, 110, 120 or 200). It will be set to 100") +# undef CL_HPP_MINIMUM_OPENCL_VERSION +# define CL_HPP_MINIMUM_OPENCL_VERSION 100 +#endif +#if CL_HPP_MINIMUM_OPENCL_VERSION > CL_HPP_TARGET_OPENCL_VERSION +# error "CL_HPP_MINIMUM_OPENCL_VERSION must not be greater than CL_HPP_TARGET_OPENCL_VERSION" +#endif + +#if CL_HPP_MINIMUM_OPENCL_VERSION <= 100 && !defined(CL_USE_DEPRECATED_OPENCL_1_0_APIS) +# define CL_USE_DEPRECATED_OPENCL_1_0_APIS +#endif +#if CL_HPP_MINIMUM_OPENCL_VERSION <= 110 && !defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) +# define CL_USE_DEPRECATED_OPENCL_1_1_APIS +#endif +#if CL_HPP_MINIMUM_OPENCL_VERSION <= 120 && !defined(CL_USE_DEPRECATED_OPENCL_1_2_APIS) +# define CL_USE_DEPRECATED_OPENCL_1_2_APIS +#endif +#if CL_HPP_MINIMUM_OPENCL_VERSION <= 200 && !defined(CL_USE_DEPRECATED_OPENCL_2_0_APIS) +# define CL_USE_DEPRECATED_OPENCL_2_0_APIS +#endif + +#ifdef _WIN32 + +#include + +#if defined(CL_HPP_USE_DX_INTEROP) +#include +#include +#endif +#endif //_WIN32 + +#if defined(_MSC_VER) +#include +#endif //_MSC_VER + +//Check for a valid C++ version + +//Need to do both tests here because for some reason __cplusplus is not +//updated in visual studio +#if (!defined(_MSC_VER) && __cplusplus < 201103L) || (defined(_MSC_VER) && _MSC_VER < 1700) +#error Visual studio 2013 or another C++11-supporting compiler required +#endif + +// +#if defined(CL_HPP_USE_CL_DEVICE_FISSION) || defined(CL_HPP_USE_CL_SUB_GROUPS_KHR) +#include +#endif + +#if defined(__APPLE__) || defined(__MACOSX) +#include +#else +#include +#endif //!__APPLE__ + +#if (__cplusplus >= 201103L) +#define CL_HPP_NOEXCEPT_ noexcept +#else +#define CL_HPP_NOEXCEPT_ +#endif + +#if defined(_MSC_VER) +# define CL_HPP_DEFINE_STATIC_MEMBER_ __declspec(selectany) +#else +# define CL_HPP_DEFINE_STATIC_MEMBER_ __attribute__((weak)) +#endif //!_MSC_VER + +//Define deprecated prefixes and suffixes to ensure compilation +//in case they are not pre-defined +#if !defined(CL_EXT_PREFIX__VERSION_1_1_DEPRECATED) +#define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED +#endif //#if !defined(CL_EXT_PREFIX__VERSION_1_1_DEPRECATED) +#if !defined(CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED) +#define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED +#endif //#if !defined(CL_EXT_PREFIX__VERSION_1_1_DEPRECATED) + +#if !defined(CL_EXT_PREFIX__VERSION_1_2_DEPRECATED) +#define CL_EXT_PREFIX__VERSION_1_2_DEPRECATED +#endif //#if !defined(CL_EXT_PREFIX__VERSION_1_2_DEPRECATED) +#if !defined(CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED) +#define CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED +#endif //#if !defined(CL_EXT_PREFIX__VERSION_1_2_DEPRECATED) + +#if !defined(CL_CALLBACK) +#define CL_CALLBACK +#endif //CL_CALLBACK + +#include +#include +#include +#include +#include +#include + +//Define a size_type to represent a correctly resolved size_t +#if defined(CL_HPP_ENABLE_SIZE_T_COMPATIBILITY) +namespace cl { +using size_type = ::size_t; +} //namespace cl +#else //#if defined(CL_HPP_ENABLE_SIZE_T_COMPATIBILITY) +namespace cl { +using size_type = size_t; +} //namespace cl +#endif //#if defined(CL_HPP_ENABLE_SIZE_T_COMPATIBILITY) + +#if defined(CL_HPP_ENABLE_EXCEPTIONS) +#include +#endif //#if defined(CL_HPP_ENABLE_EXCEPTIONS) + +#if !defined(CL_HPP_NO_STD_VECTOR) +#include +namespace cl { +template > +using vector = std::vector; +} //namespace cl +#endif //#if !defined(CL_HPP_NO_STD_VECTOR) + +#if !defined(CL_HPP_NO_STD_STRING) +#include +namespace cl { +using string = std::string; +} //namespace cl +#endif //#if !defined(CL_HPP_NO_STD_STRING) + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + +#if !defined(CL_HPP_NO_STD_UNIQUE_PTR) +#include +namespace cl { +//Replace unique_ptr and allocate_pointer for internal use +//to allow user to replace them +template +using pointer = std::unique_ptr; +} //namespace cl +#endif +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 200 +#if !defined(CL_HPP_NO_STD_ARRAY) +#include +namespace cl { +template +using array = std::array; +} //namespace cl +#endif //#if !defined(CL_HPP_NO_STD_ARRAY) + +//Define size_type appropriately to allow backward-compatibility +//use of the old size_t interface class +#if defined(CL_HPP_ENABLE_SIZE_T_COMPATIBILITY) +namespace cl { +namespace compatibility { +/*! \brief class used to interface between C++ and + * OpenCL C calls that require arrays of size_t values, whose + * size is known statically. + */ +template +class size_t +{ +private: + size_type data_[N]; + +public: + //! \brief Initialize size_t to all 0s + size_t() + { + for(int i = 0; i < N; ++i) + { + data_[i] = 0; + } + } + + size_t(const array& rhs) + { + for(int i = 0; i < N; ++i) + { + data_[i] = rhs[i]; + } + } + + size_type& operator[](int index) + { + return data_[index]; + } + + const size_type& operator[](int index) const + { + return data_[index]; + } + + //! \brief Conversion operator to T*. + operator size_type*() { + return data_; + } + + //! \brief Conversion operator to const T*. + operator const size_type*() const { return data_; + } + + operator array() const + { + array ret; + + for(int i = 0; i < N; ++i) + { + ret[i] = data_[i]; + } + + return ret; + } +}; +} //namespace compatibility + +template +using size_t = compatibility::size_t; +} //namespace cl +#endif //#if defined(CL_HPP_ENABLE_SIZE_T_COMPATIBILITY) + +//Helper alias to avoid confusing the macros +namespace cl { +namespace detail { +using size_t_array = array; +} //namespace detail +} //namespace cl + +/*! \namespace cl + * + * \brief The OpenCL C++ bindings are defined within this namespace. + * + */ +namespace cl { +class Memory; + +#define CL_HPP_INIT_CL_EXT_FCN_PTR_(name) \ + if(!pfn_ ## name){ \ + pfn_ ## name = (PFN_ ## name) \ + clGetExtensionFunctionAddress(#name); \ + if(!pfn_ ## name){ \ + } \ + } + +#define CL_HPP_INIT_CL_EXT_FCN_PTR_PLATFORM_(platform, name) \ + if(!pfn_ ## name){ \ + pfn_ ## name = (PFN_ ## name) \ + clGetExtensionFunctionAddressForPlatform(platform, #name); \ + if(!pfn_ ## name){ \ + } \ + } + +class Program; + +class Device; + +class Context; + +class CommandQueue; + +class DeviceCommandQueue; + +class Memory; + +class Buffer; + +class Pipe; + +#if defined(CL_HPP_ENABLE_EXCEPTIONS) + +/*! \brief Exception class + * + * This may be thrown by API functions when CL_HPP_ENABLE_EXCEPTIONS is defined. + */ +class Error : public std::exception +{ +private: + cl_int err_; + const char* errStr_; + +public: + /*! \brief Create a new CL error exception for a given error code + * and corresponding message. + * + * \param err error code value. + * + * \param errStr a descriptive string that must remain in scope until + * handling of the exception has concluded. If set, it + * will be returned by what(). + */ + Error(cl_int err, const char* errStr = NULL) : err_(err), errStr_(errStr) + { + } + + ~Error() throw() + { + } + + /*! \brief Get error string associated with exception + * + * \return A memory pointer to the error message string. + */ + virtual const char* what() const throw () + { + if(errStr_ == NULL) + { + return "empty"; + } + else + { + return errStr_; + } + } + + /*! \brief Get error code associated with exception + * + * \return The error code. + */ + cl_int err(void) const { + return err_; + } +}; +#define CL_HPP_ERR_STR_(x) #x +#else +#define CL_HPP_ERR_STR_(x) NULL +#endif //CL_HPP_ENABLE_EXCEPTIONS + +namespace detail +{ +#if defined(CL_HPP_ENABLE_EXCEPTIONS) +static inline cl_int errHandler ( + cl_int err, + const char* errStr = NULL) +{ + if(err != CL_SUCCESS) + { + throw Error(err, errStr); + } + + return err; +} + +#else +static inline cl_int errHandler (cl_int err, const char* errStr = NULL) +{ + (void)errStr; //suppress unused variable warning + + return err; +} + +#endif //CL_HPP_ENABLE_EXCEPTIONS +} + +//! \cond DOXYGEN_DETAIL +#if !defined(CL_HPP_USER_OVERRIDE_ERROR_STRINGS) +#define __GET_DEVICE_INFO_ERR CL_HPP_ERR_STR_(clGetDeviceInfo) +#define __GET_PLATFORM_INFO_ERR CL_HPP_ERR_STR_(clGetPlatformInfo) +#define __GET_DEVICE_IDS_ERR CL_HPP_ERR_STR_(clGetDeviceIDs) +#define __GET_PLATFORM_IDS_ERR CL_HPP_ERR_STR_(clGetPlatformIDs) +#define __GET_CONTEXT_INFO_ERR CL_HPP_ERR_STR_(clGetContextInfo) +#define __GET_EVENT_INFO_ERR CL_HPP_ERR_STR_(clGetEventInfo) +#define __GET_EVENT_PROFILE_INFO_ERR CL_HPP_ERR_STR_(clGetEventProfileInfo) +#define __GET_MEM_OBJECT_INFO_ERR CL_HPP_ERR_STR_(clGetMemObjectInfo) +#define __GET_IMAGE_INFO_ERR CL_HPP_ERR_STR_(clGetImageInfo) +#define __GET_SAMPLER_INFO_ERR CL_HPP_ERR_STR_(clGetSamplerInfo) +#define __GET_KERNEL_INFO_ERR CL_HPP_ERR_STR_(clGetKernelInfo) +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 +#define __GET_KERNEL_ARG_INFO_ERR CL_HPP_ERR_STR_(clGetKernelArgInfo) +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 +#define __GET_KERNEL_WORK_GROUP_INFO_ERR CL_HPP_ERR_STR_(clGetKernelWorkGroupInfo) +#define __GET_PROGRAM_INFO_ERR CL_HPP_ERR_STR_(clGetProgramInfo) +#define __GET_PROGRAM_BUILD_INFO_ERR CL_HPP_ERR_STR_(clGetProgramBuildInfo) +#define __GET_COMMAND_QUEUE_INFO_ERR CL_HPP_ERR_STR_(clGetCommandQueueInfo) + +#define __CREATE_CONTEXT_ERR CL_HPP_ERR_STR_(clCreateContext) +#define __CREATE_CONTEXT_FROM_TYPE_ERR CL_HPP_ERR_STR_(clCreateContextFromType) +#define __GET_SUPPORTED_IMAGE_FORMATS_ERR CL_HPP_ERR_STR_(clGetSupportedImageFormats) + +#define __CREATE_BUFFER_ERR CL_HPP_ERR_STR_(clCreateBuffer) +#define __COPY_ERR CL_HPP_ERR_STR_(cl::copy) +#define __CREATE_SUBBUFFER_ERR CL_HPP_ERR_STR_(clCreateSubBuffer) +#define __CREATE_GL_BUFFER_ERR CL_HPP_ERR_STR_(clCreateFromGLBuffer) +#define __CREATE_GL_RENDER_BUFFER_ERR CL_HPP_ERR_STR_(clCreateFromGLBuffer) +#define __GET_GL_OBJECT_INFO_ERR CL_HPP_ERR_STR_(clGetGLObjectInfo) +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 +#define __CREATE_IMAGE_ERR CL_HPP_ERR_STR_(clCreateImage) +#define __CREATE_GL_TEXTURE_ERR CL_HPP_ERR_STR_(clCreateFromGLTexture) +#define __IMAGE_DIMENSION_ERR CL_HPP_ERR_STR_(Incorrect image dimensions) +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 +#define __SET_MEM_OBJECT_DESTRUCTOR_CALLBACK_ERR CL_HPP_ERR_STR_(clSetMemObjectDestructorCallback) + +#define __CREATE_USER_EVENT_ERR CL_HPP_ERR_STR_(clCreateUserEvent) +#define __SET_USER_EVENT_STATUS_ERR CL_HPP_ERR_STR_(clSetUserEventStatus) +#define __SET_EVENT_CALLBACK_ERR CL_HPP_ERR_STR_(clSetEventCallback) +#define __WAIT_FOR_EVENTS_ERR CL_HPP_ERR_STR_(clWaitForEvents) + +#define __CREATE_KERNEL_ERR CL_HPP_ERR_STR_(clCreateKernel) +#define __SET_KERNEL_ARGS_ERR CL_HPP_ERR_STR_(clSetKernelArg) +#define __CREATE_PROGRAM_WITH_SOURCE_ERR CL_HPP_ERR_STR_(clCreateProgramWithSource) +#define __CREATE_PROGRAM_WITH_BINARY_ERR CL_HPP_ERR_STR_(clCreateProgramWithBinary) +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 +#define __CREATE_PROGRAM_WITH_BUILT_IN_KERNELS_ERR CL_HPP_ERR_STR_(clCreateProgramWithBuiltInKernels) +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 +#define __BUILD_PROGRAM_ERR CL_HPP_ERR_STR_(clBuildProgram) +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 +#define __COMPILE_PROGRAM_ERR CL_HPP_ERR_STR_(clCompileProgram) +#define __LINK_PROGRAM_ERR CL_HPP_ERR_STR_(clLinkProgram) +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 +#define __CREATE_KERNELS_IN_PROGRAM_ERR CL_HPP_ERR_STR_(clCreateKernelsInProgram) + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 +#define __CREATE_COMMAND_QUEUE_WITH_PROPERTIES_ERR CL_HPP_ERR_STR_( \ + clCreateCommandQueueWithProperties) +#define __CREATE_SAMPLER_WITH_PROPERTIES_ERR CL_HPP_ERR_STR_(clCreateSamplerWithProperties) +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 200 +#define __SET_COMMAND_QUEUE_PROPERTY_ERR CL_HPP_ERR_STR_(clSetCommandQueueProperty) +#define __ENQUEUE_READ_BUFFER_ERR CL_HPP_ERR_STR_(clEnqueueReadBuffer) +#define __ENQUEUE_READ_BUFFER_RECT_ERR CL_HPP_ERR_STR_(clEnqueueReadBufferRect) +#define __ENQUEUE_WRITE_BUFFER_ERR CL_HPP_ERR_STR_(clEnqueueWriteBuffer) +#define __ENQUEUE_WRITE_BUFFER_RECT_ERR CL_HPP_ERR_STR_(clEnqueueWriteBufferRect) +#define __ENQEUE_COPY_BUFFER_ERR CL_HPP_ERR_STR_(clEnqueueCopyBuffer) +#define __ENQEUE_COPY_BUFFER_RECT_ERR CL_HPP_ERR_STR_(clEnqueueCopyBufferRect) +#define __ENQUEUE_FILL_BUFFER_ERR CL_HPP_ERR_STR_(clEnqueueFillBuffer) +#define __ENQUEUE_READ_IMAGE_ERR CL_HPP_ERR_STR_(clEnqueueReadImage) +#define __ENQUEUE_WRITE_IMAGE_ERR CL_HPP_ERR_STR_(clEnqueueWriteImage) +#define __ENQUEUE_COPY_IMAGE_ERR CL_HPP_ERR_STR_(clEnqueueCopyImage) +#define __ENQUEUE_FILL_IMAGE_ERR CL_HPP_ERR_STR_(clEnqueueFillImage) +#define __ENQUEUE_COPY_IMAGE_TO_BUFFER_ERR CL_HPP_ERR_STR_(clEnqueueCopyImageToBuffer) +#define __ENQUEUE_COPY_BUFFER_TO_IMAGE_ERR CL_HPP_ERR_STR_(clEnqueueCopyBufferToImage) +#define __ENQUEUE_MAP_BUFFER_ERR CL_HPP_ERR_STR_(clEnqueueMapBuffer) +#define __ENQUEUE_MAP_IMAGE_ERR CL_HPP_ERR_STR_(clEnqueueMapImage) +#define __ENQUEUE_UNMAP_MEM_OBJECT_ERR CL_HPP_ERR_STR_(clEnqueueUnMapMemObject) +#define __ENQUEUE_NDRANGE_KERNEL_ERR CL_HPP_ERR_STR_(clEnqueueNDRangeKernel) +#define __ENQUEUE_NATIVE_KERNEL CL_HPP_ERR_STR_(clEnqueueNativeKernel) +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 +#define __ENQUEUE_MIGRATE_MEM_OBJECTS_ERR CL_HPP_ERR_STR_(clEnqueueMigrateMemObjects) +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 + +#define __ENQUEUE_ACQUIRE_GL_ERR CL_HPP_ERR_STR_(clEnqueueAcquireGLObjects) +#define __ENQUEUE_RELEASE_GL_ERR CL_HPP_ERR_STR_(clEnqueueReleaseGLObjects) + +#define __CREATE_PIPE_ERR CL_HPP_ERR_STR_(clCreatePipe) +#define __GET_PIPE_INFO_ERR CL_HPP_ERR_STR_(clGetPipeInfo) + +#define __RETAIN_ERR CL_HPP_ERR_STR_(Retain Object) +#define __RELEASE_ERR CL_HPP_ERR_STR_(Release Object) +#define __FLUSH_ERR CL_HPP_ERR_STR_(clFlush) +#define __FINISH_ERR CL_HPP_ERR_STR_(clFinish) +#define __VECTOR_CAPACITY_ERR CL_HPP_ERR_STR_(Vector capacity error) + +/** + * CL 1.2 version that uses device fission. + */ +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 +#define __CREATE_SUB_DEVICES_ERR CL_HPP_ERR_STR_(clCreateSubDevices) +#else +#define __CREATE_SUB_DEVICES_ERR CL_HPP_ERR_STR_(clCreateSubDevicesEXT) +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 + +/** + * Deprecated APIs for 1.2 + */ +#if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) +#define __ENQUEUE_MARKER_ERR CL_HPP_ERR_STR_(clEnqueueMarker) +#define __ENQUEUE_WAIT_FOR_EVENTS_ERR CL_HPP_ERR_STR_(clEnqueueWaitForEvents) +#define __ENQUEUE_BARRIER_ERR CL_HPP_ERR_STR_(clEnqueueBarrier) +#define __UNLOAD_COMPILER_ERR CL_HPP_ERR_STR_(clUnloadCompiler) +#define __CREATE_GL_TEXTURE_2D_ERR CL_HPP_ERR_STR_(clCreateFromGLTexture2D) +#define __CREATE_GL_TEXTURE_3D_ERR CL_HPP_ERR_STR_(clCreateFromGLTexture3D) +#define __CREATE_IMAGE2D_ERR CL_HPP_ERR_STR_(clCreateImage2D) +#define __CREATE_IMAGE3D_ERR CL_HPP_ERR_STR_(clCreateImage3D) +#endif //#if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + +/** + * Deprecated APIs for 2.0 + */ +#if defined(CL_USE_DEPRECATED_OPENCL_1_2_APIS) +#define __CREATE_COMMAND_QUEUE_ERR CL_HPP_ERR_STR_(clCreateCommandQueue) +#define __ENQUEUE_TASK_ERR CL_HPP_ERR_STR_(clEnqueueTask) +#define __CREATE_SAMPLER_ERR CL_HPP_ERR_STR_(clCreateSampler) +#endif //#if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + +/** + * CL 1.2 marker and barrier commands + */ +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 +#define __ENQUEUE_MARKER_WAIT_LIST_ERR CL_HPP_ERR_STR_(clEnqueueMarkerWithWaitList) +#define __ENQUEUE_BARRIER_WAIT_LIST_ERR CL_HPP_ERR_STR_(clEnqueueBarrierWithWaitList) +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 + +#endif //CL_HPP_USER_OVERRIDE_ERROR_STRINGS +//! \endcond + +namespace detail { +//Generic getInfoHelper. The final parameter is used to guide overload +//resolution: the actual parameter passed is an int, which makes this +//a worse conversion sequence than a specialization that declares the +//parameter as an int. +template +inline cl_int getInfoHelper(Functor f, cl_uint name, T* param, long) +{ + return f(name, sizeof(T), param, NULL); +} + +//Specialized for getInfo +//Assumes that the output vector was correctly resized on the way in +template +inline cl_int getInfoHelper(Func f, cl_uint name, vector >* param, int) +{ + if(name != CL_PROGRAM_BINARIES) + { + return CL_INVALID_VALUE; + } + if(param) + { + //Create array of pointers, calculate total size and pass pointer array in + size_type numBinaries = param->size(); + vector binariesPointers(numBinaries); + + for(size_type i = 0; i < numBinaries; ++i) + { + binariesPointers[i] = (*param)[i].data(); + } + + cl_int err = f(name, numBinaries * sizeof(unsigned char*), binariesPointers.data(), NULL); + + if(err != CL_SUCCESS) + { + return err; + } + } + + return CL_SUCCESS; +} + +//Specialized getInfoHelper for vector params +template +inline cl_int getInfoHelper(Func f, cl_uint name, vector* param, long) +{ + size_type required; + cl_int err = f(name, 0, NULL, &required); + if(err != CL_SUCCESS) + { + return err; + } + const size_type elements = required / sizeof(T); + + //Temporary to avoid changing param on an error + vector localData(elements); + err = f(name, required, localData.data(), NULL); + if(err != CL_SUCCESS) + { + return err; + } + if(param) + { + *param = std::move(localData); + } + + return CL_SUCCESS; +} + +/* Specialization for reference-counted types. This depends on the + * existence of Wrapper::cl_type, and none of the other types having the + * cl_type member. Note that simplify specifying the parameter as Wrapper + * does not work, because when using a derived type (e.g. Context) the generic + * template will provide a better match. + */ +template +inline cl_int getInfoHelper( + Func f, cl_uint name, vector* param, int, typename T::cl_type = 0) +{ + size_type required; + cl_int err = f(name, 0, NULL, &required); + if(err != CL_SUCCESS) + { + return err; + } + + const size_type elements = required / sizeof(typename T::cl_type); + + vector value(elements); + err = f(name, required, value.data(), NULL); + if(err != CL_SUCCESS) + { + return err; + } + + if(param) + { + //Assign to convert CL type to T for each element + param->resize(elements); + + //Assign to param, constructing with retain behaviour + //to correctly capture each underlying CL object + for(size_type i = 0; i < elements; i++) + { + (*param)[i] = T(value[i], true); + } + } + + return CL_SUCCESS; +} + +//Specialized GetInfoHelper for string params +template +inline cl_int getInfoHelper(Func f, cl_uint name, string* param, long) +{ + size_type required; + cl_int err = f(name, 0, NULL, &required); + if(err != CL_SUCCESS) + { + return err; + } + + //std::string has a constant data member + //a char vector does not + if(required > 0) + { + vector value(required); + err = f(name, required, value.data(), NULL); + if(err != CL_SUCCESS) + { + return err; + } + if(param) + { + param->assign(begin(value), prev(end(value))); + } + } + else + if(param) + { + param->assign(""); + } + + return CL_SUCCESS; +} + +//Specialized GetInfoHelper for clsize_t params +template +inline cl_int getInfoHelper(Func f, cl_uint name, array* param, long) +{ + size_type required; + cl_int err = f(name, 0, NULL, &required); + if(err != CL_SUCCESS) + { + return err; + } + + size_type elements = required / sizeof(size_type); + vector value(elements, 0); + + err = f(name, required, value.data(), NULL); + if(err != CL_SUCCESS) + { + return err; + } + + //Bound the copy with N to prevent overruns + //if passed N > than the amount copied + if(elements > N) + { + elements = N; + } + for(size_type i = 0; i < elements; ++i) + { + (*param)[i] = value[i]; + } + + return CL_SUCCESS; +} + +template struct ReferenceHandler; + +/* Specialization for reference-counted types. This depends on the + * existence of Wrapper::cl_type, and none of the other types having the + * cl_type member. Note that simplify specifying the parameter as Wrapper + * does not work, because when using a derived type (e.g. Context) the generic + * template will provide a better match. + */ +template +inline cl_int getInfoHelper(Func f, cl_uint name, T* param, int, typename T::cl_type = 0) +{ + typename T::cl_type value; + cl_int err = f(name, sizeof(value), &value, NULL); + if(err != CL_SUCCESS) + { + return err; + } + *param = value; + if(value != NULL) + { + err = param->retain(); + if(err != CL_SUCCESS) + { + return err; + } + } + + return CL_SUCCESS; +} + +#define CL_HPP_PARAM_NAME_INFO_1_0_(F) \ + F(cl_platform_info, CL_PLATFORM_PROFILE, string) \ + F(cl_platform_info, CL_PLATFORM_VERSION, string) \ + F(cl_platform_info, CL_PLATFORM_NAME, string) \ + F(cl_platform_info, CL_PLATFORM_VENDOR, string) \ + F(cl_platform_info, CL_PLATFORM_EXTENSIONS, string) \ + \ + F(cl_device_info, CL_DEVICE_TYPE, cl_device_type) \ + F(cl_device_info, CL_DEVICE_VENDOR_ID, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_COMPUTE_UNITS, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_WORK_GROUP_SIZE, size_type) \ + F(cl_device_info, CL_DEVICE_MAX_WORK_ITEM_SIZES, cl::vector) \ + F(cl_device_info, CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR, cl_uint) \ + F(cl_device_info, CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT, cl_uint) \ + F(cl_device_info, CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT, cl_uint) \ + F(cl_device_info, CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG, cl_uint) \ + F(cl_device_info, CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT, cl_uint) \ + F(cl_device_info, CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_CLOCK_FREQUENCY, cl_uint) \ + F(cl_device_info, CL_DEVICE_ADDRESS_BITS, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_READ_IMAGE_ARGS, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_WRITE_IMAGE_ARGS, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_MEM_ALLOC_SIZE, cl_ulong) \ + F(cl_device_info, CL_DEVICE_IMAGE2D_MAX_WIDTH, size_type) \ + F(cl_device_info, CL_DEVICE_IMAGE2D_MAX_HEIGHT, size_type) \ + F(cl_device_info, CL_DEVICE_IMAGE3D_MAX_WIDTH, size_type) \ + F(cl_device_info, CL_DEVICE_IMAGE3D_MAX_HEIGHT, size_type) \ + F(cl_device_info, CL_DEVICE_IMAGE3D_MAX_DEPTH, size_type) \ + F(cl_device_info, CL_DEVICE_IMAGE_SUPPORT, cl_bool) \ + F(cl_device_info, CL_DEVICE_MAX_PARAMETER_SIZE, size_type) \ + F(cl_device_info, CL_DEVICE_MAX_SAMPLERS, cl_uint) \ + F(cl_device_info, CL_DEVICE_MEM_BASE_ADDR_ALIGN, cl_uint) \ + F(cl_device_info, CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE, cl_uint) \ + F(cl_device_info, CL_DEVICE_SINGLE_FP_CONFIG, cl_device_fp_config) \ + F(cl_device_info, CL_DEVICE_GLOBAL_MEM_CACHE_TYPE, cl_device_mem_cache_type) \ + F(cl_device_info, CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE, cl_uint) \ + F(cl_device_info, CL_DEVICE_GLOBAL_MEM_CACHE_SIZE, cl_ulong) \ + F(cl_device_info, CL_DEVICE_GLOBAL_MEM_SIZE, cl_ulong) \ + F(cl_device_info, CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE, cl_ulong) \ + F(cl_device_info, CL_DEVICE_MAX_CONSTANT_ARGS, cl_uint) \ + F(cl_device_info, CL_DEVICE_LOCAL_MEM_TYPE, cl_device_local_mem_type) \ + F(cl_device_info, CL_DEVICE_LOCAL_MEM_SIZE, cl_ulong) \ + F(cl_device_info, CL_DEVICE_ERROR_CORRECTION_SUPPORT, cl_bool) \ + F(cl_device_info, CL_DEVICE_PROFILING_TIMER_RESOLUTION, size_type) \ + F(cl_device_info, CL_DEVICE_ENDIAN_LITTLE, cl_bool) \ + F(cl_device_info, CL_DEVICE_AVAILABLE, cl_bool) \ + F(cl_device_info, CL_DEVICE_COMPILER_AVAILABLE, cl_bool) \ + F(cl_device_info, CL_DEVICE_EXECUTION_CAPABILITIES, cl_device_exec_capabilities) \ + F(cl_device_info, CL_DEVICE_PLATFORM, cl_platform_id) \ + F(cl_device_info, CL_DEVICE_NAME, string) \ + F(cl_device_info, CL_DEVICE_VENDOR, string) \ + F(cl_device_info, CL_DRIVER_VERSION, string) \ + F(cl_device_info, CL_DEVICE_PROFILE, string) \ + F(cl_device_info, CL_DEVICE_VERSION, string) \ + F(cl_device_info, CL_DEVICE_EXTENSIONS, string) \ + \ + F(cl_context_info, CL_CONTEXT_REFERENCE_COUNT, cl_uint) \ + F(cl_context_info, CL_CONTEXT_DEVICES, cl::vector) \ + F(cl_context_info, CL_CONTEXT_PROPERTIES, cl::vector) \ + \ + F(cl_event_info, CL_EVENT_COMMAND_QUEUE, cl::CommandQueue) \ + F(cl_event_info, CL_EVENT_COMMAND_TYPE, cl_command_type) \ + F(cl_event_info, CL_EVENT_REFERENCE_COUNT, cl_uint) \ + F(cl_event_info, CL_EVENT_COMMAND_EXECUTION_STATUS, cl_int) \ + \ + F(cl_profiling_info, CL_PROFILING_COMMAND_QUEUED, cl_ulong) \ + F(cl_profiling_info, CL_PROFILING_COMMAND_SUBMIT, cl_ulong) \ + F(cl_profiling_info, CL_PROFILING_COMMAND_START, cl_ulong) \ + F(cl_profiling_info, CL_PROFILING_COMMAND_END, cl_ulong) \ + \ + F(cl_mem_info, CL_MEM_TYPE, cl_mem_object_type) \ + F(cl_mem_info, CL_MEM_FLAGS, cl_mem_flags) \ + F(cl_mem_info, CL_MEM_SIZE, size_type) \ + F(cl_mem_info, CL_MEM_HOST_PTR, void*) \ + F(cl_mem_info, CL_MEM_MAP_COUNT, cl_uint) \ + F(cl_mem_info, CL_MEM_REFERENCE_COUNT, cl_uint) \ + F(cl_mem_info, CL_MEM_CONTEXT, cl::Context) \ + \ + F(cl_image_info, CL_IMAGE_FORMAT, cl_image_format) \ + F(cl_image_info, CL_IMAGE_ELEMENT_SIZE, size_type) \ + F(cl_image_info, CL_IMAGE_ROW_PITCH, size_type) \ + F(cl_image_info, CL_IMAGE_SLICE_PITCH, size_type) \ + F(cl_image_info, CL_IMAGE_WIDTH, size_type) \ + F(cl_image_info, CL_IMAGE_HEIGHT, size_type) \ + F(cl_image_info, CL_IMAGE_DEPTH, size_type) \ + \ + F(cl_sampler_info, CL_SAMPLER_REFERENCE_COUNT, cl_uint) \ + F(cl_sampler_info, CL_SAMPLER_CONTEXT, cl::Context) \ + F(cl_sampler_info, CL_SAMPLER_NORMALIZED_COORDS, cl_bool) \ + F(cl_sampler_info, CL_SAMPLER_ADDRESSING_MODE, cl_addressing_mode) \ + F(cl_sampler_info, CL_SAMPLER_FILTER_MODE, cl_filter_mode) \ + \ + F(cl_program_info, CL_PROGRAM_REFERENCE_COUNT, cl_uint) \ + F(cl_program_info, CL_PROGRAM_CONTEXT, cl::Context) \ + F(cl_program_info, CL_PROGRAM_NUM_DEVICES, cl_uint) \ + F(cl_program_info, CL_PROGRAM_DEVICES, cl::vector) \ + F(cl_program_info, CL_PROGRAM_SOURCE, string) \ + F(cl_program_info, CL_PROGRAM_BINARY_SIZES, cl::vector) \ + F(cl_program_info, CL_PROGRAM_BINARIES, cl::vector >) \ + \ + F(cl_program_build_info, CL_PROGRAM_BUILD_STATUS, cl_build_status) \ + F(cl_program_build_info, CL_PROGRAM_BUILD_OPTIONS, string) \ + F(cl_program_build_info, CL_PROGRAM_BUILD_LOG, string) \ + \ + F(cl_kernel_info, CL_KERNEL_FUNCTION_NAME, string) \ + F(cl_kernel_info, CL_KERNEL_NUM_ARGS, cl_uint) \ + F(cl_kernel_info, CL_KERNEL_REFERENCE_COUNT, cl_uint) \ + F(cl_kernel_info, CL_KERNEL_CONTEXT, cl::Context) \ + F(cl_kernel_info, CL_KERNEL_PROGRAM, cl::Program) \ + \ + F(cl_kernel_work_group_info, CL_KERNEL_WORK_GROUP_SIZE, size_type) \ + F(cl_kernel_work_group_info, CL_KERNEL_COMPILE_WORK_GROUP_SIZE, cl::detail::size_t_array) \ + F(cl_kernel_work_group_info, CL_KERNEL_LOCAL_MEM_SIZE, cl_ulong) \ + \ + F(cl_command_queue_info, CL_QUEUE_CONTEXT, cl::Context) \ + F(cl_command_queue_info, CL_QUEUE_DEVICE, cl::Device) \ + F(cl_command_queue_info, CL_QUEUE_REFERENCE_COUNT, cl_uint) \ + F(cl_command_queue_info, CL_QUEUE_PROPERTIES, cl_command_queue_properties) + +#define CL_HPP_PARAM_NAME_INFO_1_1_(F) \ + F(cl_context_info, CL_CONTEXT_NUM_DEVICES, cl_uint) \ + F(cl_device_info, CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF, cl_uint) \ + F(cl_device_info, CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR, cl_uint) \ + F(cl_device_info, CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT, cl_uint) \ + F(cl_device_info, CL_DEVICE_NATIVE_VECTOR_WIDTH_INT, cl_uint) \ + F(cl_device_info, CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG, cl_uint) \ + F(cl_device_info, CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT, cl_uint) \ + F(cl_device_info, CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE, cl_uint) \ + F(cl_device_info, CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF, cl_uint) \ + F(cl_device_info, CL_DEVICE_DOUBLE_FP_CONFIG, cl_device_fp_config) \ + F(cl_device_info, CL_DEVICE_HALF_FP_CONFIG, cl_device_fp_config) \ + F(cl_device_info, CL_DEVICE_OPENCL_C_VERSION, string) \ + \ + F(cl_mem_info, CL_MEM_ASSOCIATED_MEMOBJECT, cl::Memory) \ + F(cl_mem_info, CL_MEM_OFFSET, size_type) \ + \ + F(cl_kernel_work_group_info, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, size_type) \ + F(cl_kernel_work_group_info, CL_KERNEL_PRIVATE_MEM_SIZE, cl_ulong) \ + \ + F(cl_event_info, CL_EVENT_CONTEXT, cl::Context) + +#define CL_HPP_PARAM_NAME_INFO_1_2_(F) \ + F(cl_program_info, CL_PROGRAM_NUM_KERNELS, size_type) \ + F(cl_program_info, CL_PROGRAM_KERNEL_NAMES, string) \ + \ + F(cl_program_build_info, CL_PROGRAM_BINARY_TYPE, cl_program_binary_type) \ + \ + F(cl_kernel_info, CL_KERNEL_ATTRIBUTES, string) \ + \ + F(cl_kernel_arg_info, CL_KERNEL_ARG_ADDRESS_QUALIFIER, cl_kernel_arg_address_qualifier) \ + F(cl_kernel_arg_info, CL_KERNEL_ARG_ACCESS_QUALIFIER, cl_kernel_arg_access_qualifier) \ + F(cl_kernel_arg_info, CL_KERNEL_ARG_TYPE_NAME, string) \ + F(cl_kernel_arg_info, CL_KERNEL_ARG_NAME, string) \ + F(cl_kernel_arg_info, CL_KERNEL_ARG_TYPE_QUALIFIER, cl_kernel_arg_type_qualifier) \ + \ + F(cl_device_info, CL_DEVICE_PARENT_DEVICE, cl::Device) \ + F(cl_device_info, CL_DEVICE_PARTITION_PROPERTIES, cl::vector) \ + F(cl_device_info, CL_DEVICE_PARTITION_TYPE, cl::vector) \ + F(cl_device_info, CL_DEVICE_REFERENCE_COUNT, cl_uint) \ + F(cl_device_info, CL_DEVICE_PREFERRED_INTEROP_USER_SYNC, size_type) \ + F(cl_device_info, CL_DEVICE_PARTITION_AFFINITY_DOMAIN, cl_device_affinity_domain) \ + F(cl_device_info, CL_DEVICE_BUILT_IN_KERNELS, string) \ + \ + F(cl_image_info, CL_IMAGE_ARRAY_SIZE, size_type) \ + F(cl_image_info, CL_IMAGE_NUM_MIP_LEVELS, cl_uint) \ + F(cl_image_info, CL_IMAGE_NUM_SAMPLES, cl_uint) + +#define CL_HPP_PARAM_NAME_INFO_2_0_(F) \ + F(cl_device_info, CL_DEVICE_QUEUE_ON_HOST_PROPERTIES, cl_command_queue_properties) \ + F(cl_device_info, CL_DEVICE_QUEUE_ON_DEVICE_PROPERTIES, cl_command_queue_properties) \ + F(cl_device_info, CL_DEVICE_QUEUE_ON_DEVICE_PREFERRED_SIZE, cl_uint) \ + F(cl_device_info, CL_DEVICE_QUEUE_ON_DEVICE_MAX_SIZE, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_ON_DEVICE_QUEUES, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_ON_DEVICE_EVENTS, cl_uint) \ + F(cl_device_info, CL_DEVICE_MAX_PIPE_ARGS, cl_uint) \ + F(cl_device_info, CL_DEVICE_PIPE_MAX_ACTIVE_RESERVATIONS, cl_uint) \ + F(cl_device_info, CL_DEVICE_PIPE_MAX_PACKET_SIZE, cl_uint) \ + F(cl_device_info, CL_DEVICE_SVM_CAPABILITIES, cl_device_svm_capabilities) \ + F(cl_device_info, CL_DEVICE_PREFERRED_PLATFORM_ATOMIC_ALIGNMENT, cl_uint) \ + F(cl_device_info, CL_DEVICE_PREFERRED_GLOBAL_ATOMIC_ALIGNMENT, cl_uint) \ + F(cl_device_info, CL_DEVICE_PREFERRED_LOCAL_ATOMIC_ALIGNMENT, cl_uint) \ + F(cl_command_queue_info, CL_QUEUE_SIZE, cl_uint) \ + F(cl_mem_info, CL_MEM_USES_SVM_POINTER, cl_bool) \ + F(cl_program_build_info, CL_PROGRAM_BUILD_GLOBAL_VARIABLE_TOTAL_SIZE, size_type) \ + F(cl_pipe_info, CL_PIPE_PACKET_SIZE, cl_uint) \ + F(cl_pipe_info, CL_PIPE_MAX_PACKETS, cl_uint) + +#define CL_HPP_PARAM_NAME_DEVICE_FISSION_(F) \ + F(cl_device_info, CL_DEVICE_PARENT_DEVICE_EXT, cl_device_id) \ + F(cl_device_info, CL_DEVICE_PARTITION_TYPES_EXT, cl::vector) \ + F(cl_device_info, CL_DEVICE_AFFINITY_DOMAINS_EXT, cl::vector) \ + F(cl_device_info, CL_DEVICE_REFERENCE_COUNT_EXT, cl_uint) \ + F(cl_device_info, CL_DEVICE_PARTITION_STYLE_EXT, cl::vector) + +template +struct param_traits {}; + +#define CL_HPP_DECLARE_PARAM_TRAITS_(token, param_name, T) \ + struct token; \ + template<> \ + struct param_traits \ + { \ + enum { value = param_name }; \ + typedef T param_type; \ + }; + +CL_HPP_PARAM_NAME_INFO_1_0_(CL_HPP_DECLARE_PARAM_TRAITS_) +#if CL_HPP_TARGET_OPENCL_VERSION >= 110 +CL_HPP_PARAM_NAME_INFO_1_1_(CL_HPP_DECLARE_PARAM_TRAITS_) +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 110 +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 +CL_HPP_PARAM_NAME_INFO_1_2_(CL_HPP_DECLARE_PARAM_TRAITS_) +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 110 +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 +CL_HPP_PARAM_NAME_INFO_2_0_(CL_HPP_DECLARE_PARAM_TRAITS_) +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 110 + +//Flags deprecated in OpenCL 2.0 +#define CL_HPP_PARAM_NAME_INFO_1_0_DEPRECATED_IN_2_0_(F) \ + F(cl_device_info, CL_DEVICE_QUEUE_PROPERTIES, cl_command_queue_properties) + +#define CL_HPP_PARAM_NAME_INFO_1_1_DEPRECATED_IN_2_0_(F) \ + F(cl_device_info, CL_DEVICE_HOST_UNIFIED_MEMORY, cl_bool) + +#define CL_HPP_PARAM_NAME_INFO_1_2_DEPRECATED_IN_2_0_(F) \ + F(cl_image_info, CL_IMAGE_BUFFER, cl::Buffer) + +//Include deprecated query flags based on versions +//Only include deprecated 1.0 flags if 2.0 not active as there is an enum clash +#if CL_HPP_TARGET_OPENCL_VERSION > 100 && CL_HPP_MINIMUM_OPENCL_VERSION < 200 && \ + CL_HPP_TARGET_OPENCL_VERSION < 200 +CL_HPP_PARAM_NAME_INFO_1_0_DEPRECATED_IN_2_0_(CL_HPP_DECLARE_PARAM_TRAITS_) +#endif //CL_HPP_MINIMUM_OPENCL_VERSION < 110 +#if CL_HPP_TARGET_OPENCL_VERSION > 110 && CL_HPP_MINIMUM_OPENCL_VERSION < 200 +CL_HPP_PARAM_NAME_INFO_1_1_DEPRECATED_IN_2_0_(CL_HPP_DECLARE_PARAM_TRAITS_) +#endif //CL_HPP_MINIMUM_OPENCL_VERSION < 120 +#if CL_HPP_TARGET_OPENCL_VERSION > 120 && CL_HPP_MINIMUM_OPENCL_VERSION < 200 +CL_HPP_PARAM_NAME_INFO_1_2_DEPRECATED_IN_2_0_(CL_HPP_DECLARE_PARAM_TRAITS_) +#endif //CL_HPP_MINIMUM_OPENCL_VERSION < 200 + +#if defined(CL_HPP_USE_CL_DEVICE_FISSION) +CL_HPP_PARAM_NAME_DEVICE_FISSION_(CL_HPP_DECLARE_PARAM_TRAITS_); +#endif //CL_HPP_USE_CL_DEVICE_FISSION + +#ifdef CL_PLATFORM_ICD_SUFFIX_KHR +CL_HPP_DECLARE_PARAM_TRAITS_(cl_platform_info, CL_PLATFORM_ICD_SUFFIX_KHR, string) +#endif + +#ifdef CL_DEVICE_PROFILING_TIMER_OFFSET_AMD +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_PROFILING_TIMER_OFFSET_AMD, cl_ulong) +#endif + +#ifdef CL_DEVICE_GLOBAL_FREE_MEMORY_AMD +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_GLOBAL_FREE_MEMORY_AMD, vector) +#endif +#ifdef CL_DEVICE_SIMD_PER_COMPUTE_UNIT_AMD +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_SIMD_PER_COMPUTE_UNIT_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_SIMD_WIDTH_AMD +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_SIMD_WIDTH_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_SIMD_INSTRUCTION_WIDTH_AMD +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_SIMD_INSTRUCTION_WIDTH_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_WAVEFRONT_WIDTH_AMD +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_WAVEFRONT_WIDTH_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_GLOBAL_MEM_CHANNELS_AMD +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_GLOBAL_MEM_CHANNELS_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_GLOBAL_MEM_CHANNEL_BANKS_AMD +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_GLOBAL_MEM_CHANNEL_BANKS_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_GLOBAL_MEM_CHANNEL_BANK_WIDTH_AMD +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_GLOBAL_MEM_CHANNEL_BANK_WIDTH_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_LOCAL_MEM_SIZE_PER_COMPUTE_UNIT_AMD +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_LOCAL_MEM_SIZE_PER_COMPUTE_UNIT_AMD, cl_uint) +#endif +#ifdef CL_DEVICE_LOCAL_MEM_BANKS_AMD +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_LOCAL_MEM_BANKS_AMD, cl_uint) +#endif + +#ifdef CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV, cl_uint) +#endif +#ifdef CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV, cl_uint) +#endif +#ifdef CL_DEVICE_REGISTERS_PER_BLOCK_NV +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_REGISTERS_PER_BLOCK_NV, cl_uint) +#endif +#ifdef CL_DEVICE_WARP_SIZE_NV +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_WARP_SIZE_NV, cl_uint) +#endif +#ifdef CL_DEVICE_GPU_OVERLAP_NV +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_GPU_OVERLAP_NV, cl_bool) +#endif +#ifdef CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV, cl_bool) +#endif +#ifdef CL_DEVICE_INTEGRATED_MEMORY_NV +CL_HPP_DECLARE_PARAM_TRAITS_(cl_device_info, CL_DEVICE_INTEGRATED_MEMORY_NV, cl_bool) +#endif + +//Convenience functions + +template +inline cl_int getInfo(Func f, cl_uint name, T* param) +{ + return getInfoHelper(f, name, param, 0); +} + +template +struct GetInfoFunctor0 +{ + Func f_; + const Arg0& arg0_; + cl_int operator()( + cl_uint param, size_type size, void* value, size_type* size_ret) + { + return f_(arg0_, param, size, value, size_ret); + } +}; + +template +struct GetInfoFunctor1 +{ + Func f_; + const Arg0& arg0_; + const Arg1& arg1_; + cl_int operator()( + cl_uint param, size_type size, void* value, size_type* size_ret) + { + return f_(arg0_, arg1_, param, size, value, size_ret); + } +}; + +template +inline cl_int getInfo(Func f, const Arg0& arg0, cl_uint name, T* param) +{ + GetInfoFunctor0 f0 = { f, arg0 }; + + return getInfoHelper(f0, name, param, 0); +} + +template +inline cl_int getInfo(Func f, const Arg0& arg0, const Arg1& arg1, cl_uint name, T* param) +{ + GetInfoFunctor1 f0 = { f, arg0, arg1 }; + + return getInfoHelper(f0, name, param, 0); +} + +template +struct ReferenceHandler +{ }; + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 +/** + * OpenCL 1.2 devices do have retain/release. + */ +template<> +struct ReferenceHandler +{ + /** + * Retain the device. + * \param device A valid device created using createSubDevices + * \return + * CL_SUCCESS if the function executed successfully. + * CL_INVALID_DEVICE if device was not a valid subdevice + * CL_OUT_OF_RESOURCES + * CL_OUT_OF_HOST_MEMORY + */ + static cl_int retain(cl_device_id device) + { + return ::clRetainDevice(device); + } + + /** + * Retain the device. + * \param device A valid device created using createSubDevices + * \return + * CL_SUCCESS if the function executed successfully. + * CL_INVALID_DEVICE if device was not a valid subdevice + * CL_OUT_OF_RESOURCES + * CL_OUT_OF_HOST_MEMORY + */ + static cl_int release(cl_device_id device) + { + return ::clReleaseDevice(device); + } +}; + +#else //CL_HPP_TARGET_OPENCL_VERSION >= 120 +/** + * OpenCL 1.1 devices do not have retain/release. + */ +template<> +struct ReferenceHandler +{ + //cl_device_id does not have retain(). + static cl_int retain(cl_device_id) + { + return CL_SUCCESS; + } + + //cl_device_id does not have release(). + static cl_int release(cl_device_id) + { + return CL_SUCCESS; + } +}; + +#endif //! (CL_HPP_TARGET_OPENCL_VERSION >= 120) + +template<> +struct ReferenceHandler +{ + //cl_platform_id does not have retain(). + static cl_int retain(cl_platform_id) + { + return CL_SUCCESS; + } + + //cl_platform_id does not have release(). + static cl_int release(cl_platform_id) + { + return CL_SUCCESS; + } +}; + +template<> +struct ReferenceHandler +{ + static cl_int retain(cl_context context) + { + return ::clRetainContext(context); + } + + static cl_int release(cl_context context) + { + return ::clReleaseContext(context); + } +}; + +template<> +struct ReferenceHandler +{ + static cl_int retain(cl_command_queue queue) + { + return ::clRetainCommandQueue(queue); + } + + static cl_int release(cl_command_queue queue) + { + return ::clReleaseCommandQueue(queue); + } +}; + +template<> +struct ReferenceHandler +{ + static cl_int retain(cl_mem memory) + { + return ::clRetainMemObject(memory); + } + + static cl_int release(cl_mem memory) + { + return ::clReleaseMemObject(memory); + } +}; + +template<> +struct ReferenceHandler +{ + static cl_int retain(cl_sampler sampler) + { + return ::clRetainSampler(sampler); + } + + static cl_int release(cl_sampler sampler) + { + return ::clReleaseSampler(sampler); + } +}; + +template<> +struct ReferenceHandler +{ + static cl_int retain(cl_program program) + { + return ::clRetainProgram(program); + } + + static cl_int release(cl_program program) + { + return ::clReleaseProgram(program); + } +}; + +template<> +struct ReferenceHandler +{ + static cl_int retain(cl_kernel kernel) + { + return ::clRetainKernel(kernel); + } + + static cl_int release(cl_kernel kernel) + { + return ::clReleaseKernel(kernel); + } +}; + +template<> +struct ReferenceHandler +{ + static cl_int retain(cl_event event) + { + return ::clRetainEvent(event); + } + + static cl_int release(cl_event event) + { + return ::clReleaseEvent(event); + } +}; + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 && CL_HPP_MINIMUM_OPENCL_VERSION < 120 +//Extracts version number with major in the upper 16 bits, minor in the lower 16 +static cl_uint getVersion(const vector& versionInfo) +{ + int highVersion = 0; + int lowVersion = 0; + int index = 7; + while(versionInfo[index] != '.') + { + highVersion *= 10; + highVersion += versionInfo[index] - '0'; + ++index; + } + ++index; + while(versionInfo[index] != ' ' && versionInfo[index] != '\0') + { + lowVersion *= 10; + lowVersion += versionInfo[index] - '0'; + ++index; + } + + return (highVersion << 16) | lowVersion; +} + +static cl_uint getPlatformVersion(cl_platform_id platform) +{ + size_type size = 0; + clGetPlatformInfo(platform, CL_PLATFORM_VERSION, 0, NULL, &size); + + vector versionInfo(size); + clGetPlatformInfo(platform, CL_PLATFORM_VERSION, size, versionInfo.data(), &size); + + return getVersion(versionInfo); +} + +static cl_uint getDevicePlatformVersion(cl_device_id device) +{ + cl_platform_id platform; + clGetDeviceInfo(device, CL_DEVICE_PLATFORM, sizeof(platform), &platform, NULL); + + return getPlatformVersion(platform); +} + +static cl_uint getContextPlatformVersion(cl_context context) +{ + //The platform cannot be queried directly, so we first have to grab a + //device and obtain its context + size_type size = 0; + clGetContextInfo(context, CL_CONTEXT_DEVICES, 0, NULL, &size); + if(size == 0) + { + return 0; + } + vector devices(size / sizeof(cl_device_id)); + clGetContextInfo(context, CL_CONTEXT_DEVICES, size, devices.data(), NULL); + + return getDevicePlatformVersion(devices[0]); +} + +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 && CL_HPP_MINIMUM_OPENCL_VERSION < 120 + +template +class Wrapper +{ +public: + typedef T cl_type; + +protected: + cl_type object_; + +public: + Wrapper() : object_(NULL) + { + } + + Wrapper(const cl_type& obj, bool retainObject) : object_(obj) + { + if(retainObject) + { + detail::errHandler(retain(), __RETAIN_ERR); + } + } + + ~Wrapper() + { + if(object_ != NULL) + { + release(); + } + } + + Wrapper(const Wrapper& rhs) + { + object_ = rhs.object_; + detail::errHandler(retain(), __RETAIN_ERR); + } + + Wrapper(Wrapper&& rhs) CL_HPP_NOEXCEPT_ + { + object_ = rhs.object_; + rhs.object_ = NULL; + } + + Wrapper& operator= (const Wrapper& rhs) + { + if(this != &rhs) + { + detail::errHandler(release(), __RELEASE_ERR); + object_ = rhs.object_; + detail::errHandler(retain(), __RETAIN_ERR); + } + + return *this; + } + + Wrapper& operator= (Wrapper&& rhs) + { + if(this != &rhs) + { + detail::errHandler(release(), __RELEASE_ERR); + object_ = rhs.object_; + rhs.object_ = NULL; + } + + return *this; + } + + Wrapper& operator= (const cl_type& rhs) + { + detail::errHandler(release(), __RELEASE_ERR); + object_ = rhs; + + return *this; + } + + const cl_type& operator()() const { + return object_; + } + + cl_type& operator()() { + return object_; + } + + const cl_type get() const { + return object_; + } + + cl_type get() { + return object_; + } + +protected: + template + friend inline cl_int getInfoHelper(Func, cl_uint, U*, int, typename U::cl_type); + + cl_int retain() const + { + if(object_ != nullptr) + { + return ReferenceHandler::retain(object_); + } + else + { + return CL_SUCCESS; + } + } + + cl_int release() const + { + if(object_ != nullptr) + { + return ReferenceHandler::release(object_); + } + else + { + return CL_SUCCESS; + } + } +}; + +template<> +class Wrapper +{ +public: + typedef cl_device_id cl_type; + +protected: + cl_type object_; + bool referenceCountable_; + + static bool isReferenceCountable(cl_device_id device) + { + bool retVal = false; +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 +#if CL_HPP_MINIMUM_OPENCL_VERSION < 120 + if(device != NULL) + { + int version = getDevicePlatformVersion(device); + if(version > ((1 << 16) + 1)) + { + retVal = true; + } + } +#else //CL_HPP_MINIMUM_OPENCL_VERSION < 120 + retVal = true; +#endif //CL_HPP_MINIMUM_OPENCL_VERSION < 120 +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 + + return retVal; + } + +public: + Wrapper() : object_(NULL), referenceCountable_(false) + { + } + + Wrapper(const cl_type& obj, bool retainObject) : + object_(obj), + referenceCountable_(false) + { + referenceCountable_ = isReferenceCountable(obj); + + if(retainObject) + { + detail::errHandler(retain(), __RETAIN_ERR); + } + } + + ~Wrapper() + { + release(); + } + + Wrapper(const Wrapper& rhs) + { + object_ = rhs.object_; + referenceCountable_ = isReferenceCountable(object_); + detail::errHandler(retain(), __RETAIN_ERR); + } + + Wrapper(Wrapper&& rhs) CL_HPP_NOEXCEPT_ + { + object_ = rhs.object_; + referenceCountable_ = rhs.referenceCountable_; + rhs.object_ = NULL; + rhs.referenceCountable_ = false; + } + + Wrapper& operator= (const Wrapper& rhs) + { + if(this != &rhs) + { + detail::errHandler(release(), __RELEASE_ERR); + object_ = rhs.object_; + referenceCountable_ = rhs.referenceCountable_; + detail::errHandler(retain(), __RETAIN_ERR); + } + + return *this; + } + + Wrapper& operator= (Wrapper&& rhs) + { + if(this != &rhs) + { + detail::errHandler(release(), __RELEASE_ERR); + object_ = rhs.object_; + referenceCountable_ = rhs.referenceCountable_; + rhs.object_ = NULL; + rhs.referenceCountable_ = false; + } + + return *this; + } + + Wrapper& operator= (const cl_type& rhs) + { + detail::errHandler(release(), __RELEASE_ERR); + object_ = rhs; + referenceCountable_ = isReferenceCountable(object_); + + return *this; + } + + const cl_type& operator()() const { + return object_; + } + + cl_type& operator()() { + return object_; + } + + const cl_type get() const { + return object_; + } + + cl_type get() { + return object_; + } + +protected: + template + friend inline cl_int getInfoHelper(Func, cl_uint, U*, int, typename U::cl_type); + + template + friend inline cl_int getInfoHelper(Func, cl_uint, vector*, int, typename U::cl_type); + + cl_int retain() const + { + if(object_ != nullptr && referenceCountable_) + { + return ReferenceHandler::retain(object_); + } + else + { + return CL_SUCCESS; + } + } + + cl_int release() const + { + if(object_ != nullptr && referenceCountable_) + { + return ReferenceHandler::release(object_); + } + else + { + return CL_SUCCESS; + } + } +}; + +template +inline bool operator==(const Wrapper& lhs, const Wrapper& rhs) +{ + return lhs() == rhs(); +} + +template +inline bool operator!=(const Wrapper& lhs, const Wrapper& rhs) +{ + return !operator==(lhs, rhs); +} +} //namespace detail +//! \endcond + +using BuildLogType = vector::param_type> >; +#if defined(CL_HPP_ENABLE_EXCEPTIONS) + +/** + * Exception class for build errors to carry build info + */ +class BuildError : public Error +{ +private: + BuildLogType buildLogs; + +public: + BuildError(cl_int err, const char* errStr, const BuildLogType& vec) : Error(err, errStr), + buildLogs(vec) + { + } + + BuildLogType getBuildLog() const + { + return buildLogs; + } +}; +namespace detail { +static inline cl_int buildErrHandler( + cl_int err, + const char* errStr, + const BuildLogType& buildLogs) +{ + if(err != CL_SUCCESS) + { + throw BuildError(err, errStr, buildLogs); + } + + return err; +} +} //namespace detail + +#else +namespace detail { +static inline cl_int buildErrHandler( + cl_int err, + const char* errStr, + const BuildLogType& buildLogs) +{ + (void)buildLogs; //suppress unused variable warning + (void)errStr; + + return err; +} +} //namespace detail +#endif //#if defined(CL_HPP_ENABLE_EXCEPTIONS) + +/*! \stuct ImageFormat + * \brief Adds constructors and member functions for cl_image_format. + * + * \see cl_image_format + */ +struct ImageFormat : public cl_image_format +{ + //! \brief Default constructor - performs no initialization. + ImageFormat() + { + } + + //! \brief Initializing constructor. + ImageFormat(cl_channel_order order, cl_channel_type type) + { + image_channel_order = order; + image_channel_data_type = type; + } + + //! \brief Assignment operator. + ImageFormat& operator= (const ImageFormat& rhs) + { + if(this != &rhs) + { + this->image_channel_data_type = rhs.image_channel_data_type; + this->image_channel_order = rhs.image_channel_order; + } + + return *this; + } +}; + +/*! \brief Class interface for cl_device_id. + * + * \note Copies of these objects are inexpensive, since they don't 'own' + * any underlying resources or data structures. + * + * \see cl_device_id + */ +class Device : public detail::Wrapper +{ +private: + static std::once_flag default_initialized_; + static Device default_; + static cl_int default_error_; + + /*! \brief Create the default context. + * + * This sets @c default_ and @c default_error_. It does not throw + * @c cl::Error. + */ + static void makeDefault(); + + /*! \brief Create the default platform from a provided platform. + * + * This sets @c default_. It does not throw + * @c cl::Error. + */ + static void makeDefaultProvided(const Device& p) { + default_ = p; + } + +public: +#ifdef CL_HPP_UNIT_TEST_ENABLE + /*! \brief Reset the default. + * + * This sets @c default_ to an empty value to support cleanup in + * the unit test framework. + * This function is not thread safe. + */ + static void unitTestClearDefault() { + default_ = Device(); + } + +#endif //#ifdef CL_HPP_UNIT_TEST_ENABLE + + //! \brief Default constructor - initializes to NULL. + Device() : detail::Wrapper() + { + } + + /*! \brief Constructor from cl_device_id. + * + * This simply copies the device ID value, which is an inexpensive operation. + */ + explicit Device(const cl_device_id& device, bool retainObject = false) : + detail::Wrapper(device, retainObject) + { + } + + /*! \brief Returns the first device on the default context. + * + * \see Context::getDefault() + */ + static Device getDefault( + cl_int* errResult = NULL) + { + std::call_once(default_initialized_, makeDefault); + detail::errHandler(default_error_); + if(errResult != NULL) + { + *errResult = default_error_; + } + + return default_; + } + + /** + * Modify the default device to be used by + * subsequent operations. + * Will only set the default if no default was previously created. + * @return updated default device. + * Should be compared to the passed value to ensure that it was updated. + */ + static Device setDefault(const Device& default_device) + { + std::call_once(default_initialized_, makeDefaultProvided, std::cref(default_device)); + detail::errHandler(default_error_); + + return default_; + } + + /*! \brief Assignment operator from cl_device_id. + * + * This simply copies the device ID value, which is an inexpensive operation. + */ + Device& operator= (const cl_device_id& rhs) + { + detail::Wrapper::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Device(const Device& dev) : detail::Wrapper(dev) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Device& operator= (const Device& dev) + { + detail::Wrapper::operator=(dev); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Device(Device&& dev) CL_HPP_NOEXCEPT_ : detail::Wrapper(std::move(dev)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Device& operator= (Device&& dev) + { + detail::Wrapper::operator=(std::move(dev)); + + return *this; + } + + //! \brief Wrapper for clGetDeviceInfo(). + template + cl_int getInfo(cl_device_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetDeviceInfo, object_, name, param), + __GET_DEVICE_INFO_ERR); + } + + //! \brief Wrapper for clGetDeviceInfo() that returns by value. + template typename + detail::param_traits::param_type getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_device_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } + + /** + * CL 1.2 version + */ +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + //! \brief Wrapper for clCreateSubDevices(). + cl_int createSubDevices( + const cl_device_partition_property* properties, + vector* devices) + { + cl_uint n = 0; + cl_int err = clCreateSubDevices(object_, properties, 0, NULL, &n); + if(err != CL_SUCCESS) + { + return detail::errHandler(err, __CREATE_SUB_DEVICES_ERR); + } + + vector ids(n); + err = clCreateSubDevices(object_, properties, n, ids.data(), NULL); + if(err != CL_SUCCESS) + { + return detail::errHandler(err, __CREATE_SUB_DEVICES_ERR); + } + + //Cannot trivially assign because we need to capture intermediates + //with safe construction + if(devices) + { + devices->resize(ids.size()); + + //Assign to param, constructing with retain behaviour + //to correctly capture each underlying CL object + for(size_type i = 0; i < ids.size(); i++) + { + //We do not need to retain because this device is being created + //by the runtime + (*devices)[i] = Device(ids[i], false); + } + } + + return CL_SUCCESS; + } + +#elif defined(CL_HPP_USE_CL_DEVICE_FISSION) + +/** + * CL 1.1 version that uses device fission extension. + */ + cl_int createSubDevices( + const cl_device_partition_property_ext* properties, + vector* devices) + { + typedef CL_API_ENTRY cl_int + (CL_API_CALL* PFN_clCreateSubDevicesEXT)( + cl_device_id /*in_device*/, + const cl_device_partition_property_ext* /* properties */, + cl_uint /*num_entries*/, + cl_device_id* /*out_devices*/, + cl_uint* /*num_devices*/) CL_EXT_SUFFIX__VERSION_1_1; + + static PFN_clCreateSubDevicesEXT pfn_clCreateSubDevicesEXT = NULL; + CL_HPP_INIT_CL_EXT_FCN_PTR_(clCreateSubDevicesEXT); + + cl_uint n = 0; + cl_int err = pfn_clCreateSubDevicesEXT(object_, properties, 0, NULL, &n); + if(err != CL_SUCCESS) + { + return detail::errHandler(err, __CREATE_SUB_DEVICES_ERR); + } + + vector ids(n); + err = pfn_clCreateSubDevicesEXT(object_, properties, n, ids.data(), NULL); + if(err != CL_SUCCESS) + { + return detail::errHandler(err, __CREATE_SUB_DEVICES_ERR); + } + //Cannot trivially assign because we need to capture intermediates + //with safe construction + if(devices) + { + devices->resize(ids.size()); + + //Assign to param, constructing with retain behaviour + //to correctly capture each underlying CL object + for(size_type i = 0; i < ids.size(); i++) + { + //We do not need to retain because this device is being created + //by the runtime + (*devices)[i] = Device(ids[i], false); + } + } + + return CL_SUCCESS; + } + +#endif //defined(CL_HPP_USE_CL_DEVICE_FISSION) +}; + +CL_HPP_DEFINE_STATIC_MEMBER_ std::once_flag Device::default_initialized_; +CL_HPP_DEFINE_STATIC_MEMBER_ Device Device::default_; +CL_HPP_DEFINE_STATIC_MEMBER_ cl_int Device::default_error_ = CL_SUCCESS; + +/*! \brief Class interface for cl_platform_id. + * + * \note Copies of these objects are inexpensive, since they don't 'own' + * any underlying resources or data structures. + * + * \see cl_platform_id + */ +class Platform : public detail::Wrapper +{ +private: + static std::once_flag default_initialized_; + static Platform default_; + static cl_int default_error_; + + /*! \brief Create the default context. + * + * This sets @c default_ and @c default_error_. It does not throw + * @c cl::Error. + */ + static void makeDefault() { + /* Throwing an exception from a call_once invocation does not do + * what we wish, so we catch it and save the error. + */ +#if defined(CL_HPP_ENABLE_EXCEPTIONS) + try +#endif + { + //If default wasn't passed ,generate one + //Otherwise set it + cl_uint n = 0; + + cl_int err = ::clGetPlatformIDs(0, NULL, &n); + if(err != CL_SUCCESS) + { + default_error_ = err; + + return; + } + if(n == 0) + { + default_error_ = CL_INVALID_PLATFORM; + + return; + } + + vector ids(n); + err = ::clGetPlatformIDs(n, ids.data(), NULL); + if(err != CL_SUCCESS) + { + default_error_ = err; + + return; + } + + default_ = Platform(ids[0]); + } +#if defined(CL_HPP_ENABLE_EXCEPTIONS) + catch(cl::Error& e) + { + default_error_ = e.err(); + } +#endif + } + + /*! \brief Create the default platform from a provided platform. + * + * This sets @c default_. It does not throw + * @c cl::Error. + */ + static void makeDefaultProvided(const Platform& p) { + default_ = p; + } + +public: +#ifdef CL_HPP_UNIT_TEST_ENABLE + /*! \brief Reset the default. + * + * This sets @c default_ to an empty value to support cleanup in + * the unit test framework. + * This function is not thread safe. + */ + static void unitTestClearDefault() { + default_ = Platform(); + } + +#endif //#ifdef CL_HPP_UNIT_TEST_ENABLE + + //! \brief Default constructor - initializes to NULL. + Platform() : detail::Wrapper() + { + } + + /*! \brief Constructor from cl_platform_id. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * This simply copies the platform ID value, which is an inexpensive operation. + */ + explicit Platform(const cl_platform_id& platform, bool retainObject = false) : + detail::Wrapper(platform, retainObject) + { + } + + /*! \brief Assignment operator from cl_platform_id. + * + * This simply copies the platform ID value, which is an inexpensive operation. + */ + Platform& operator= (const cl_platform_id& rhs) + { + detail::Wrapper::operator=(rhs); + + return *this; + } + + static Platform getDefault( + cl_int* errResult = NULL) + { + std::call_once(default_initialized_, makeDefault); + detail::errHandler(default_error_); + if(errResult != NULL) + { + *errResult = default_error_; + } + + return default_; + } + + /** + * Modify the default platform to be used by + * subsequent operations. + * Will only set the default if no default was previously created. + * @return updated default platform. + * Should be compared to the passed value to ensure that it was updated. + */ + static Platform setDefault(const Platform& default_platform) + { + std::call_once(default_initialized_, makeDefaultProvided, std::cref(default_platform)); + detail::errHandler(default_error_); + + return default_; + } + + //! \brief Wrapper for clGetPlatformInfo(). + cl_int getInfo(cl_platform_info name, string* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetPlatformInfo, object_, name, param), + __GET_PLATFORM_INFO_ERR); + } + + //! \brief Wrapper for clGetPlatformInfo() that returns by value. + template typename + detail::param_traits::param_type getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_platform_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } + + /*! \brief Gets a list of devices for this platform. + * + * Wraps clGetDeviceIDs(). + */ + cl_int getDevices( + cl_device_type type, + vector* devices) const + { + cl_uint n = 0; + if(devices == NULL) + { + return detail::errHandler(CL_INVALID_ARG_VALUE, __GET_DEVICE_IDS_ERR); + } + cl_int err = ::clGetDeviceIDs(object_, type, 0, NULL, &n); + if(err != CL_SUCCESS) + { + return detail::errHandler(err, __GET_DEVICE_IDS_ERR); + } + + vector ids(n); + err = ::clGetDeviceIDs(object_, type, n, ids.data(), NULL); + if(err != CL_SUCCESS) + { + return detail::errHandler(err, __GET_DEVICE_IDS_ERR); + } + + //Cannot trivially assign because we need to capture intermediates + //with safe construction + //We must retain things we obtain from the API to avoid releasing + //API-owned objects. + if(devices) + { + devices->resize(ids.size()); + + //Assign to param, constructing with retain behaviour + //to correctly capture each underlying CL object + for(size_type i = 0; i < ids.size(); i++) + { + (*devices)[i] = Device(ids[i], true); + } + } + + return CL_SUCCESS; + } + +#if defined(CL_HPP_USE_DX_INTEROP) + /*! \brief Get the list of available D3D10 devices. + * + * \param d3d_device_source. + * + * \param d3d_object. + * + * \param d3d_device_set. + * + * \param devices returns a vector of OpenCL D3D10 devices found. The cl::Device + * values returned in devices can be used to identify a specific OpenCL + * device. If \a devices argument is NULL, this argument is ignored. + * + * \return One of the following values: + * - CL_SUCCESS if the function is executed successfully. + * + * The application can query specific capabilities of the OpenCL device(s) + * returned by cl::getDevices. This can be used by the application to + * determine which device(s) to use. + * + * \note In the case that exceptions are enabled and a return value + * other than CL_SUCCESS is generated, then cl::Error exception is + * generated. + */ + cl_int getDevices( + cl_d3d10_device_source_khr d3d_device_source, + void* d3d_object, + cl_d3d10_device_set_khr d3d_device_set, + vector* devices) const + { + typedef CL_API_ENTRY cl_int (CL_API_CALL* PFN_clGetDeviceIDsFromD3D10KHR)( + cl_platform_id platform, + cl_d3d10_device_source_khr d3d_device_source, + void* d3d_object, + cl_d3d10_device_set_khr d3d_device_set, + cl_uint num_entries, + cl_device_id* devices, + cl_uint* num_devices); + + if(devices == NULL) + { + return detail::errHandler(CL_INVALID_ARG_VALUE, __GET_DEVICE_IDS_ERR); + } + + static PFN_clGetDeviceIDsFromD3D10KHR pfn_clGetDeviceIDsFromD3D10KHR = NULL; + CL_HPP_INIT_CL_EXT_FCN_PTR_PLATFORM_(object_, clGetDeviceIDsFromD3D10KHR); + + cl_uint n = 0; + cl_int err = pfn_clGetDeviceIDsFromD3D10KHR( + object_, + d3d_device_source, + d3d_object, + d3d_device_set, + 0, + NULL, + &n); + if(err != CL_SUCCESS) + { + return detail::errHandler(err, __GET_DEVICE_IDS_ERR); + } + + vector ids(n); + err = pfn_clGetDeviceIDsFromD3D10KHR( + object_, + d3d_device_source, + d3d_object, + d3d_device_set, + n, + ids.data(), + NULL); + if(err != CL_SUCCESS) + { + return detail::errHandler(err, __GET_DEVICE_IDS_ERR); + } + + //Cannot trivially assign because we need to capture intermediates + //with safe construction + //We must retain things we obtain from the API to avoid releasing + //API-owned objects. + if(devices) + { + devices->resize(ids.size()); + + //Assign to param, constructing with retain behaviour + //to correctly capture each underlying CL object + for(size_type i = 0; i < ids.size(); i++) + { + (*devices)[i] = Device(ids[i], true); + } + } + + return CL_SUCCESS; + } + +#endif + + /*! \brief Gets a list of available platforms. + * + * Wraps clGetPlatformIDs(). + */ + static cl_int get( + vector* platforms) + { + cl_uint n = 0; + + if(platforms == NULL) + { + return detail::errHandler(CL_INVALID_ARG_VALUE, __GET_PLATFORM_IDS_ERR); + } + + cl_int err = ::clGetPlatformIDs(0, NULL, &n); + if(err != CL_SUCCESS) + { + return detail::errHandler(err, __GET_PLATFORM_IDS_ERR); + } + + vector ids(n); + err = ::clGetPlatformIDs(n, ids.data(), NULL); + if(err != CL_SUCCESS) + { + return detail::errHandler(err, __GET_PLATFORM_IDS_ERR); + } + + if(platforms) + { + platforms->resize(ids.size()); + + //Platforms don't reference count + for(size_type i = 0; i < ids.size(); i++) + { + (*platforms)[i] = Platform(ids[i]); + } + } + + return CL_SUCCESS; + } + + /*! \brief Gets the first available platform. + * + * Wraps clGetPlatformIDs(), returning the first result. + */ + static cl_int get( + Platform* platform) + { + cl_int err; + Platform default_platform = Platform::getDefault(&err); + if(platform) + { + *platform = default_platform; + } + + return err; + } + + /*! \brief Gets the first available platform, returning it by value. + * + * \return Returns a valid platform if one is available. + * If no platform is available will return a null platform. + * Throws an exception if no platforms are available + * or an error condition occurs. + * Wraps clGetPlatformIDs(), returning the first result. + */ + static Platform get( + cl_int* errResult = NULL) + { + cl_int err; + Platform default_platform = Platform::getDefault(&err); + if(errResult) + { + *errResult = err; + } + + return default_platform; + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + //! \brief Wrapper for clUnloadCompiler(). + cl_int unloadCompiler() + { + return ::clUnloadPlatformCompiler(object_); + } + +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 +}; //class Platform + +CL_HPP_DEFINE_STATIC_MEMBER_ std::once_flag Platform::default_initialized_; +CL_HPP_DEFINE_STATIC_MEMBER_ Platform Platform::default_; +CL_HPP_DEFINE_STATIC_MEMBER_ cl_int Platform::default_error_ = CL_SUCCESS; + +/** + * Deprecated APIs for 1.2 + */ +#if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) +/** + * Unload the OpenCL compiler. + * \note Deprecated for OpenCL 1.2. Use Platform::unloadCompiler instead. + */ +inline CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int +UnloadCompiler() CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; +inline cl_int UnloadCompiler() +{ + return ::clUnloadCompiler(); +} + +#endif //#if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + +/*! \brief Class interface for cl_context. + * + * \note Copies of these objects are shallow, meaning that the copy will refer + * to the same underlying cl_context as the original. For details, see + * clRetainContext() and clReleaseContext(). + * + * \see cl_context + */ +class Context + : public detail::Wrapper +{ +private: + static std::once_flag default_initialized_; + static Context default_; + static cl_int default_error_; + + /*! \brief Create the default context from the default device type in the default platform. + * + * This sets @c default_ and @c default_error_. It does not throw + * @c cl::Error. + */ + static void makeDefault() { + /* Throwing an exception from a call_once invocation does not do + * what we wish, so we catch it and save the error. + */ +#if defined(CL_HPP_ENABLE_EXCEPTIONS) + try +#endif + { +#if !defined(__APPLE__) && !defined(__MACOS) + const Platform& p = Platform::getDefault(); + cl_platform_id defaultPlatform = p(); + cl_context_properties properties[3] = { + CL_CONTEXT_PLATFORM, (cl_context_properties)defaultPlatform, 0 + }; +#else //#if !defined(__APPLE__) && !defined(__MACOS) + cl_context_properties* properties = nullptr; +#endif //#if !defined(__APPLE__) && !defined(__MACOS) + + default_ = Context( + CL_DEVICE_TYPE_DEFAULT, + properties, + NULL, + NULL, + &default_error_); + } +#if defined(CL_HPP_ENABLE_EXCEPTIONS) + catch(cl::Error& e) + { + default_error_ = e.err(); + } +#endif + } + + /*! \brief Create the default context from a provided Context. + * + * This sets @c default_. It does not throw + * @c cl::Error. + */ + static void makeDefaultProvided(const Context& c) { + default_ = c; + } + +public: +#ifdef CL_HPP_UNIT_TEST_ENABLE + /*! \brief Reset the default. + * + * This sets @c default_ to an empty value to support cleanup in + * the unit test framework. + * This function is not thread safe. + */ + static void unitTestClearDefault() { + default_ = Context(); + } + +#endif //#ifdef CL_HPP_UNIT_TEST_ENABLE + + /*! \brief Constructs a context including a list of specified devices. + * + * Wraps clCreateContext(). + */ + Context( + const vector& devices, + cl_context_properties* properties = NULL, + void(CL_CALLBACK * notifyFptr)( + const char*, + const void*, + size_type, + void*) = NULL, + void* data = NULL, + cl_int* err = NULL) + { + cl_int error; + + size_type numDevices = devices.size(); + vector deviceIDs(numDevices); + + for(size_type deviceIndex = 0; deviceIndex < numDevices; ++deviceIndex) + { + deviceIDs[deviceIndex] = (devices[deviceIndex])(); + } + + object_ = ::clCreateContext( + properties, (cl_uint)numDevices, + deviceIDs.data(), + notifyFptr, data, &error); + + detail::errHandler(error, __CREATE_CONTEXT_ERR); + if(err != NULL) + { + *err = error; + } + } + + Context( + const Device& device, + cl_context_properties* properties = NULL, + void(CL_CALLBACK * notifyFptr)( + const char*, + const void*, + size_type, + void*) = NULL, + void* data = NULL, + cl_int* err = NULL) + { + cl_int error; + + cl_device_id deviceID = device(); + + object_ = ::clCreateContext( + properties, 1, + &deviceID, + notifyFptr, data, &error); + + detail::errHandler(error, __CREATE_CONTEXT_ERR); + if(err != NULL) + { + *err = error; + } + } + + /*! \brief Constructs a context including all or a subset of devices of a specified type. + * + * Wraps clCreateContextFromType(). + */ + Context( + cl_device_type type, + cl_context_properties* properties = NULL, + void(CL_CALLBACK * notifyFptr)( + const char*, + const void*, + size_type, + void*) = NULL, + void* data = NULL, + cl_int* err = NULL) + { + cl_int error; + +#if !defined(__APPLE__) && !defined(__MACOS) + cl_context_properties prop[4] = {CL_CONTEXT_PLATFORM, 0, 0, 0 }; + + if(properties == NULL) + { + //Get a valid platform ID as we cannot send in a blank one + vector platforms; + error = Platform::get(&platforms); + if(error != CL_SUCCESS) + { + detail::errHandler(error, __CREATE_CONTEXT_FROM_TYPE_ERR); + if(err != NULL) + { + *err = error; + } + + return; + } + + //Check the platforms we found for a device of our specified type + cl_context_properties platform_id = 0; + for(unsigned int i = 0; i < platforms.size(); i++) + { + vector devices; + +#if defined(CL_HPP_ENABLE_EXCEPTIONS) + try { +#endif + + error = platforms[i].getDevices(type, &devices); + +#if defined(CL_HPP_ENABLE_EXCEPTIONS) + } + catch(Error) + { + } + //Catch if exceptions are enabled as we don't want to exit if first platform has no + //devices of type + //We do error checking next anyway, and can throw there if needed +#endif + + //Only squash CL_SUCCESS and CL_DEVICE_NOT_FOUND + if(error != CL_SUCCESS && error != CL_DEVICE_NOT_FOUND) + { + detail::errHandler(error, __CREATE_CONTEXT_FROM_TYPE_ERR); + if(err != NULL) + { + *err = error; + } + } + + if(devices.size() > 0) + { + platform_id = (cl_context_properties)platforms[i](); + break; + } + } + + if(platform_id == 0) + { + detail::errHandler(CL_DEVICE_NOT_FOUND, __CREATE_CONTEXT_FROM_TYPE_ERR); + if(err != NULL) + { + *err = CL_DEVICE_NOT_FOUND; + } + + return; + } + + prop[1] = platform_id; + properties = &prop[0]; + } +#endif + object_ = ::clCreateContextFromType( + properties, type, notifyFptr, data, &error); + + detail::errHandler(error, __CREATE_CONTEXT_FROM_TYPE_ERR); + if(err != NULL) + { + *err = error; + } + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Context(const Context& ctx) : detail::Wrapper(ctx) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Context& operator= (const Context& ctx) + { + detail::Wrapper::operator=(ctx); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Context(Context&& ctx) CL_HPP_NOEXCEPT_ : detail::Wrapper(std::move(ctx)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Context& operator= (Context&& ctx) + { + detail::Wrapper::operator=(std::move(ctx)); + + return *this; + } + + /*! \brief Returns a singleton context including all devices of CL_DEVICE_TYPE_DEFAULT. + * + * \note All calls to this function return the same cl_context as the first. + */ + static Context getDefault(cl_int* err = NULL) + { + std::call_once(default_initialized_, makeDefault); + detail::errHandler(default_error_); + if(err != NULL) + { + *err = default_error_; + } + + return default_; + } + + /** + * Modify the default context to be used by + * subsequent operations. + * Will only set the default if no default was previously created. + * @return updated default context. + * Should be compared to the passed value to ensure that it was updated. + */ + static Context setDefault(const Context& default_context) + { + std::call_once(default_initialized_, makeDefaultProvided, std::cref(default_context)); + detail::errHandler(default_error_); + + return default_; + } + + //! \brief Default constructor - initializes to NULL. + Context() : detail::Wrapper() + { + } + + /*! \brief Constructor from cl_context - takes ownership. + * + * This effectively transfers ownership of a refcount on the cl_context + * into the new Context object. + */ + explicit Context(const cl_context& context, bool retainObject = false) : + detail::Wrapper(context, retainObject) + { + } + + /*! \brief Assignment operator from cl_context - takes ownership. + * + * This effectively transfers ownership of a refcount on the rhs and calls + * clReleaseContext() on the value previously held by this instance. + */ + Context& operator= (const cl_context& rhs) + { + detail::Wrapper::operator=(rhs); + + return *this; + } + + //! \brief Wrapper for clGetContextInfo(). + template + cl_int getInfo(cl_context_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetContextInfo, object_, name, param), + __GET_CONTEXT_INFO_ERR); + } + + //! \brief Wrapper for clGetContextInfo() that returns by value. + template typename + detail::param_traits::param_type getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_context_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } + + /*! \brief Gets a list of supported image formats. + * + * Wraps clGetSupportedImageFormats(). + */ + cl_int getSupportedImageFormats( + cl_mem_flags flags, + cl_mem_object_type type, + vector* formats) const + { + cl_uint numEntries; + + if(!formats) + { + return CL_SUCCESS; + } + + cl_int err = ::clGetSupportedImageFormats( + object_, + flags, + type, + 0, + NULL, + &numEntries); + if(err != CL_SUCCESS) + { + return detail::errHandler(err, __GET_SUPPORTED_IMAGE_FORMATS_ERR); + } + + if(numEntries > 0) + { + vector value(numEntries); + err = ::clGetSupportedImageFormats( + object_, + flags, + type, + numEntries, + (cl_image_format*)value.data(), + NULL); + if(err != CL_SUCCESS) + { + return detail::errHandler(err, __GET_SUPPORTED_IMAGE_FORMATS_ERR); + } + + formats->assign(begin(value), end(value)); + } + else + { + //If no values are being returned, ensure an empty vector comes back + formats->clear(); + } + + return CL_SUCCESS; + } +}; + +inline void Device::makeDefault() +{ + /* Throwing an exception from a call_once invocation does not do + * what we wish, so we catch it and save the error. + */ +#if defined(CL_HPP_ENABLE_EXCEPTIONS) + try +#endif + { + cl_int error = 0; + + Context context = Context::getDefault(&error); + detail::errHandler(error, __CREATE_CONTEXT_ERR); + + if(error != CL_SUCCESS) + { + default_error_ = error; + } + else + { + default_ = context.getInfo()[0]; + default_error_ = CL_SUCCESS; + } + } +#if defined(CL_HPP_ENABLE_EXCEPTIONS) + catch(cl::Error& e) + { + default_error_ = e.err(); + } +#endif +} + +CL_HPP_DEFINE_STATIC_MEMBER_ std::once_flag Context::default_initialized_; +CL_HPP_DEFINE_STATIC_MEMBER_ Context Context::default_; +CL_HPP_DEFINE_STATIC_MEMBER_ cl_int Context::default_error_ = CL_SUCCESS; + +/*! \brief Class interface for cl_event. + * + * \note Copies of these objects are shallow, meaning that the copy will refer + * to the same underlying cl_event as the original. For details, see + * clRetainEvent() and clReleaseEvent(). + * + * \see cl_event + */ +class Event : public detail::Wrapper +{ +public: + //! \brief Default constructor - initializes to NULL. + Event() : detail::Wrapper() + { + } + + /*! \brief Constructor from cl_event - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * This effectively transfers ownership of a refcount on the cl_event + * into the new Event object. + */ + explicit Event(const cl_event& event, bool retainObject = false) : + detail::Wrapper(event, retainObject) + { + } + + /*! \brief Assignment operator from cl_event - takes ownership. + * + * This effectively transfers ownership of a refcount on the rhs and calls + * clReleaseEvent() on the value previously held by this instance. + */ + Event& operator= (const cl_event& rhs) + { + detail::Wrapper::operator=(rhs); + + return *this; + } + + //! \brief Wrapper for clGetEventInfo(). + template + cl_int getInfo(cl_event_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetEventInfo, object_, name, param), + __GET_EVENT_INFO_ERR); + } + + //! \brief Wrapper for clGetEventInfo() that returns by value. + template typename + detail::param_traits::param_type getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_event_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } + + //! \brief Wrapper for clGetEventProfilingInfo(). + template + cl_int getProfilingInfo(cl_profiling_info name, T* param) const + { + return detail::errHandler(detail::getInfo( + &::clGetEventProfilingInfo, object_, name, param), + __GET_EVENT_PROFILE_INFO_ERR); + } + + //! \brief Wrapper for clGetEventProfilingInfo() that returns by value. + template typename + detail::param_traits::param_type getProfilingInfo( + cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_profiling_info, name>::param_type param; + cl_int result = getProfilingInfo(name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } + + /*! \brief Blocks the calling thread until this event completes. + * + * Wraps clWaitForEvents(). + */ + cl_int wait() const + { + return detail::errHandler( + ::clWaitForEvents(1, &object_), + __WAIT_FOR_EVENTS_ERR); + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 110 + /*! \brief Registers a user callback function for a specific command execution status. + * + * Wraps clSetEventCallback(). + */ + cl_int setCallback( + cl_int type, + void(CL_CALLBACK* pfn_notify)(cl_event, cl_int, void*), + void* user_data = NULL) + { + return detail::errHandler( + ::clSetEventCallback( + object_, + type, + pfn_notify, + user_data), + __SET_EVENT_CALLBACK_ERR); + } + +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 110 + + /*! \brief Blocks the calling thread until every event specified is complete. + * + * Wraps clWaitForEvents(). + */ + static cl_int waitForEvents(const vector& events) + { + return detail::errHandler( + ::clWaitForEvents( + (cl_uint)events.size(), (events.size() > 0) ? (cl_event*)&events.front() : NULL), + __WAIT_FOR_EVENTS_ERR); + } +}; + +#if CL_HPP_TARGET_OPENCL_VERSION >= 110 + +/*! \brief Class interface for user events (a subset of cl_event's). + * + * See Event for details about copy semantics, etc. + */ +class UserEvent : public Event +{ +public: + /*! \brief Constructs a user event on a given context. + * + * Wraps clCreateUserEvent(). + */ + UserEvent( + const Context& context, + cl_int* err = NULL) + { + cl_int error; + object_ = ::clCreateUserEvent( + context(), + &error); + + detail::errHandler(error, __CREATE_USER_EVENT_ERR); + if(err != NULL) + { + *err = error; + } + } + + //! \brief Default constructor - initializes to NULL. + UserEvent() : Event() + { + } + + /*! \brief Sets the execution status of a user event object. + * + * Wraps clSetUserEventStatus(). + */ + cl_int setStatus(cl_int status) + { + return detail::errHandler( + ::clSetUserEventStatus(object_, status), + __SET_USER_EVENT_STATUS_ERR); + } +}; +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 110 + +/*! \brief Blocks the calling thread until every event specified is complete. + * + * Wraps clWaitForEvents(). + */ +inline static cl_int WaitForEvents(const vector& events) +{ + return detail::errHandler( + ::clWaitForEvents( + (cl_uint)events.size(), (events.size() > 0) ? (cl_event*)&events.front() : NULL), + __WAIT_FOR_EVENTS_ERR); +} + +/*! \brief Class interface for cl_mem. + * + * \note Copies of these objects are shallow, meaning that the copy will refer + * to the same underlying cl_mem as the original. For details, see + * clRetainMemObject() and clReleaseMemObject(). + * + * \see cl_mem + */ +class Memory : public detail::Wrapper +{ +public: + //! \brief Default constructor - initializes to NULL. + Memory() : detail::Wrapper() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * Optionally transfer ownership of a refcount on the cl_mem + * into the new Memory object. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * + * See Memory for further details. + */ + explicit Memory(const cl_mem& memory, bool retainObject) : + detail::Wrapper(memory, retainObject) + { + } + + /*! \brief Assignment operator from cl_mem - takes ownership. + * + * This effectively transfers ownership of a refcount on the rhs and calls + * clReleaseMemObject() on the value previously held by this instance. + */ + Memory& operator= (const cl_mem& rhs) + { + detail::Wrapper::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Memory(const Memory& mem) : detail::Wrapper(mem) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Memory& operator= (const Memory& mem) + { + detail::Wrapper::operator=(mem); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Memory(Memory&& mem) CL_HPP_NOEXCEPT_ : detail::Wrapper(std::move(mem)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Memory& operator= (Memory&& mem) + { + detail::Wrapper::operator=(std::move(mem)); + + return *this; + } + + //! \brief Wrapper for clGetMemObjectInfo(). + template + cl_int getInfo(cl_mem_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetMemObjectInfo, object_, name, param), + __GET_MEM_OBJECT_INFO_ERR); + } + + //! \brief Wrapper for clGetMemObjectInfo() that returns by value. + template typename + detail::param_traits::param_type getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_mem_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 110 + /*! \brief Registers a callback function to be called when the memory object + * is no longer needed. + * + * Wraps clSetMemObjectDestructorCallback(). + * + * Repeated calls to this function, for a given cl_mem value, will append + * to the list of functions called (in reverse order) when memory object's + * resources are freed and the memory object is deleted. + * + * \note + * The registered callbacks are associated with the underlying cl_mem + * value - not the Memory class instance. + */ + cl_int setDestructorCallback( + void(CL_CALLBACK* pfn_notify)(cl_mem, void*), + void* user_data = NULL) + { + return detail::errHandler( + ::clSetMemObjectDestructorCallback( + object_, + pfn_notify, + user_data), + __SET_MEM_OBJECT_DESTRUCTOR_CALLBACK_ERR); + } + +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 110 +}; + +//Pre-declare copy functions +class Buffer; +template +cl_int copy(IteratorType startIterator, IteratorType endIterator, cl::Buffer& buffer); +template +cl_int copy(const cl::Buffer& buffer, IteratorType startIterator, IteratorType endIterator); +template +cl_int copy(const CommandQueue& queue, + IteratorType startIterator, + IteratorType endIterator, + cl::Buffer& buffer); +template +cl_int copy(const CommandQueue& queue, + const cl::Buffer& buffer, + IteratorType startIterator, + IteratorType endIterator); + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 +namespace detail +{ +class SVMTraitNull +{ +public: + static cl_svm_mem_flags getSVMMemFlags() + { + return 0; + } +}; +} //namespace detail + +template +class SVMTraitReadWrite +{ +public: + static cl_svm_mem_flags getSVMMemFlags() + { + return CL_MEM_READ_WRITE | + Trait::getSVMMemFlags(); + } +}; + +template +class SVMTraitReadOnly +{ +public: + static cl_svm_mem_flags getSVMMemFlags() + { + return CL_MEM_READ_ONLY | + Trait::getSVMMemFlags(); + } +}; + +template +class SVMTraitWriteOnly +{ +public: + static cl_svm_mem_flags getSVMMemFlags() + { + return CL_MEM_WRITE_ONLY | + Trait::getSVMMemFlags(); + } +}; + +template > +class SVMTraitCoarse +{ +public: + static cl_svm_mem_flags getSVMMemFlags() + { + return Trait::getSVMMemFlags(); + } +}; + +template > +class SVMTraitFine +{ +public: + static cl_svm_mem_flags getSVMMemFlags() + { + return CL_MEM_SVM_FINE_GRAIN_BUFFER | + Trait::getSVMMemFlags(); + } +}; + +template > +class SVMTraitAtomic +{ +public: + static cl_svm_mem_flags getSVMMemFlags() + { + return + CL_MEM_SVM_FINE_GRAIN_BUFFER | + CL_MEM_SVM_ATOMICS | + Trait::getSVMMemFlags(); + } +}; + +//Pre-declare SVM map function +template +inline cl_int enqueueMapSVM( + T* ptr, + cl_bool blocking, + cl_map_flags flags, + size_type size, + const vector* events = NULL, + Event* event = NULL); + +/** + * STL-like allocator class for managing SVM objects provided for convenience. + * + * Note that while this behaves like an allocator for the purposes of constructing vectors and + *similar objects, + * care must be taken when using with smart pointers. + * The allocator should not be used to construct a unique_ptr if we are using coarse-grained SVM + *mode because + * the coarse-grained management behaviour would behave incorrectly with respect to reference + *counting. + * + * Instead the allocator embeds a Deleter which may be used with unique_ptr and is used + * with the allocate_shared and allocate_ptr supplied operations. + */ +template +class SVMAllocator +{ +private: + Context context_; + +public: + typedef T value_type; + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef value_type& reference; + typedef const value_type& const_reference; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; + + template + struct rebind + { + typedef SVMAllocator other; + }; + + template + friend class SVMAllocator; + + SVMAllocator() : + context_(Context::getDefault()) + { + } + + explicit SVMAllocator(cl::Context context) : + context_(context) + { + } + + SVMAllocator(const SVMAllocator& other) : + context_(other.context_) + { + } + + template + SVMAllocator(const SVMAllocator& other) : + context_(other.context_) + { + } + + ~SVMAllocator() + { + } + + pointer address(reference r) CL_HPP_NOEXCEPT_ + { + return std::addressof(r); + } + + const_pointer address(const_reference r) CL_HPP_NOEXCEPT_ + { + return std::addressof(r); + } + + /** + * Allocate an SVM pointer. + * + * If the allocator is coarse-grained, this will take ownership to allow + * containers to correctly construct data in place. + */ + pointer allocate( + size_type size, + typename cl::SVMAllocator::const_pointer = 0) + { + //Allocate memory with default alignment matching the size of the type + void* voidPointer = + clSVMAlloc( + context_(), + SVMTrait::getSVMMemFlags(), + size * sizeof(T), + 0); + pointer retValue = reinterpret_cast( + voidPointer); +#if defined(CL_HPP_ENABLE_EXCEPTIONS) + if(!retValue) + { + std::bad_alloc excep; + throw excep; + } +#endif //#if defined(CL_HPP_ENABLE_EXCEPTIONS) + + //If allocation was coarse-grained then map it + if(!(SVMTrait::getSVMMemFlags() & CL_MEM_SVM_FINE_GRAIN_BUFFER)) + { + cl_int err = + enqueueMapSVM(retValue, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, size * sizeof(T)); + if(err != CL_SUCCESS) + { + std::bad_alloc excep; + throw excep; + } + } + + //If exceptions disabled, return null pointer from allocator + return retValue; + } + + void deallocate(pointer p, size_type) + { + clSVMFree(context_(), p); + } + + /** + * Return the maximum possible allocation size. + * This is the minimum of the maximum sizes of all devices in the context. + */ + size_type max_size() const CL_HPP_NOEXCEPT_ + { + size_type maxSize = std::numeric_limits::max() / sizeof(T); + + for(Device& d : context_.getInfo()) + { + maxSize = std::min( + maxSize, + static_cast(d.getInfo())); + } + + return maxSize; + } + + template + void construct(U* p, Args&&... args) + { + new(p)T(args ...); + } + + template + void destroy(U* p) + { + p->~U(); + } + + /** + * Returns true if the contexts match. + */ + inline bool operator==(SVMAllocator const& rhs) + { + return (context_ == rhs.context_); + } + + inline bool operator!=(SVMAllocator const& a) + { + return !operator==(a); + } +}; //class SVMAllocator return cl::pointer(tmp, detail::Deleter{alloc, copies}); + +template +class SVMAllocator +{ +public: + typedef void value_type; + typedef value_type* pointer; + typedef const value_type* const_pointer; + + template + struct rebind + { + typedef SVMAllocator other; + }; + + template + friend class SVMAllocator; +}; + +#if !defined(CL_HPP_NO_STD_UNIQUE_PTR) +namespace detail +{ +template +class Deleter +{ +private: + Alloc alloc_; + size_type copies_; + +public: + typedef typename std::allocator_traits::pointer pointer; + + Deleter(const Alloc& alloc, size_type copies) : alloc_{alloc}, copies_{copies} + { + } + + void operator()(pointer ptr) const { + Alloc tmpAlloc{ alloc_ }; + std::allocator_traits::destroy(tmpAlloc, std::addressof(*ptr)); + std::allocator_traits::deallocate(tmpAlloc, ptr, copies_); + } +}; +} //namespace detail + +/** + * Allocation operation compatible with std::allocate_ptr. + * Creates a unique_ptr by default. + * This requirement is to ensure that the control block is not + * allocated in memory inaccessible to the host. + */ +template +cl::pointer > allocate_pointer(const Alloc& alloc_, Args&&... args) +{ + Alloc alloc(alloc_); + static const size_type copies = 1; + + //Ensure that creation of the management block and the + //object are dealt with separately such that we only provide a deleter + + T* tmp = std::allocator_traits::allocate(alloc, copies); + if(!tmp) + { + std::bad_alloc excep; + throw excep; + } + try { + std::allocator_traits::construct( + alloc, + std::addressof(*tmp), + std::forward(args) ...); + + return cl::pointer >(tmp, detail::Deleter{alloc, copies}); + } + catch(std::bad_alloc b) + { + std::allocator_traits::deallocate(alloc, tmp, copies); + throw; + } +} + +template +cl::pointer > > allocate_svm(Args... args) +{ + SVMAllocator alloc; + + return cl::allocate_pointer(alloc, args ...); +} + +template +cl::pointer > > allocate_svm(const cl::Context& c, + Args... args) +{ + SVMAllocator alloc(c); + + return cl::allocate_pointer(alloc, args ...); +} + +#endif //#if !defined(CL_HPP_NO_STD_UNIQUE_PTR) + +/*! \brief Vector alias to simplify contruction of coarse-grained SVM containers. + * + */ +template +using coarse_svm_vector = vector > >; + +/*! \brief Vector alias to simplify contruction of fine-grained SVM containers. + * + */ +template +using fine_svm_vector = vector > >; + +/*! \brief Vector alias to simplify contruction of fine-grained SVM containers that support platform + atomics. + * + */ +template +using atomic_svm_vector = vector > >; + +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + +/*! \brief Class interface for Buffer Memory Objects. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class Buffer : public Memory +{ +public: + /*! \brief Constructs a Buffer in a specified context. + * + * Wraps clCreateBuffer(). + * + * \param host_ptr Storage to be used if the CL_MEM_USE_HOST_PTR flag was + * specified. Note alignment & exclusivity requirements. + */ + Buffer( + const Context& context, + cl_mem_flags flags, + size_type size, + void* host_ptr = NULL, + cl_int* err = NULL) + { + cl_int error; + object_ = ::clCreateBuffer(context(), flags, size, host_ptr, &error); + + detail::errHandler(error, __CREATE_BUFFER_ERR); + if(err != NULL) + { + *err = error; + } + } + + /*! \brief Constructs a Buffer in the default context. + * + * Wraps clCreateBuffer(). + * + * \param host_ptr Storage to be used if the CL_MEM_USE_HOST_PTR flag was + * specified. Note alignment & exclusivity requirements. + * + * \see Context::getDefault() + */ + Buffer( + cl_mem_flags flags, + size_type size, + void* host_ptr = NULL, + cl_int* err = NULL) + { + cl_int error; + + Context context = Context::getDefault(err); + + object_ = ::clCreateBuffer(context(), flags, size, host_ptr, &error); + + detail::errHandler(error, __CREATE_BUFFER_ERR); + if(err != NULL) + { + *err = error; + } + } + + /*! + * \brief Construct a Buffer from a host container via iterators. + * IteratorType must be random access. + * If useHostPtr is specified iterators must represent contiguous data. + */ + template + Buffer( + IteratorType startIterator, + IteratorType endIterator, + bool readOnly, + bool useHostPtr = false, + cl_int* err = NULL) + { + typedef typename std::iterator_traits::value_type DataType; + cl_int error; + + cl_mem_flags flags = 0; + if(readOnly) + { + flags |= CL_MEM_READ_ONLY; + } + else + { + flags |= CL_MEM_READ_WRITE; + } + if(useHostPtr) + { + flags |= CL_MEM_USE_HOST_PTR; + } + + size_type size = sizeof(DataType) * (endIterator - startIterator); + + Context context = Context::getDefault(err); + + if(useHostPtr) + { + object_ = + ::clCreateBuffer(context(), + flags, + size, + static_cast(&*startIterator), + &error); + } + else + { + object_ = ::clCreateBuffer(context(), flags, size, 0, &error); + } + + detail::errHandler(error, __CREATE_BUFFER_ERR); + if(err != NULL) + { + *err = error; + } + + if(!useHostPtr) + { + error = cl::copy(startIterator, endIterator, *this); + detail::errHandler(error, __CREATE_BUFFER_ERR); + if(err != NULL) + { + *err = error; + } + } + } + + /*! + * \brief Construct a Buffer from a host container via iterators using a specified context. + * IteratorType must be random access. + * If useHostPtr is specified iterators must represent contiguous data. + */ + template + Buffer(const Context& context, IteratorType startIterator, IteratorType endIterator, + bool readOnly, bool useHostPtr = false, cl_int* err = NULL); + + /*! + * \brief Construct a Buffer from a host container via iterators using a specified queue. + * If useHostPtr is specified iterators must be random access. + */ + template + Buffer(const CommandQueue& queue, IteratorType startIterator, IteratorType endIterator, + bool readOnly, bool useHostPtr = false, cl_int* err = NULL); + + //! \brief Default constructor - initializes to NULL. + Buffer() : Memory() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with earlier versions. + * + * See Memory for further details. + */ + explicit Buffer(const cl_mem& buffer, bool retainObject = false) : + Memory(buffer, retainObject) + { + } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + Buffer& operator= (const cl_mem& rhs) + { + Memory::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Buffer(const Buffer& buf) : Memory(buf) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Buffer& operator= (const Buffer& buf) + { + Memory::operator=(buf); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Buffer(Buffer&& buf) CL_HPP_NOEXCEPT_ : Memory(std::move(buf)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Buffer& operator= (Buffer&& buf) + { + Memory::operator=(std::move(buf)); + + return *this; + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 110 + /*! \brief Creates a new buffer object from this. + * + * Wraps clCreateSubBuffer(). + */ + Buffer createSubBuffer( + cl_mem_flags flags, + cl_buffer_create_type buffer_create_type, + const void* buffer_create_info, + cl_int* err = NULL) + { + Buffer result; + cl_int error; + result.object_ = ::clCreateSubBuffer( + object_, + flags, + buffer_create_type, + buffer_create_info, + &error); + + detail::errHandler(error, __CREATE_SUBBUFFER_ERR); + if(err != NULL) + { + *err = error; + } + + return result; + } + +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 110 +}; + +#if defined (CL_HPP_USE_DX_INTEROP) + +/*! \brief Class interface for creating OpenCL buffers from ID3D10Buffer's. + * + * This is provided to facilitate interoperability with Direct3D. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class BufferD3D10 : public Buffer +{ +public: + /*! \brief Constructs a BufferD3D10, in a specified context, from a + * given ID3D10Buffer. + * + * Wraps clCreateFromD3D10BufferKHR(). + */ + BufferD3D10( + const Context& context, + cl_mem_flags flags, + ID3D10Buffer* bufobj, + cl_int* err = NULL) : pfn_clCreateFromD3D10BufferKHR(nullptr) + { + typedef CL_API_ENTRY cl_mem (CL_API_CALL* PFN_clCreateFromD3D10BufferKHR)( + cl_context context, cl_mem_flags flags, ID3D10Buffer* buffer, + cl_int* errcode_ret); + PFN_clCreateFromD3D10BufferKHR pfn_clCreateFromD3D10BufferKHR; +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + vector props = context.getInfo(); + cl_platform platform = -1; + for(int i = 0; i < props.size(); ++i) + { + if(props[i] == CL_CONTEXT_PLATFORM) + { + platform = props[i + 1]; + } + } + CL_HPP_INIT_CL_EXT_FCN_PTR_PLATFORM_(platform, clCreateFromD3D10BufferKHR); +#elif CL_HPP_TARGET_OPENCL_VERSION >= 110 + CL_HPP_INIT_CL_EXT_FCN_PTR_(clCreateFromD3D10BufferKHR); +#endif + + cl_int error; + object_ = pfn_clCreateFromD3D10BufferKHR( + context(), + flags, + bufobj, + &error); + + detail::errHandler(error, __CREATE_GL_BUFFER_ERR); + if(err != NULL) + { + *err = error; + } + } + + //! \brief Default constructor - initializes to NULL. + BufferD3D10() : Buffer() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * See Memory for further details. + */ + explicit BufferD3D10(const cl_mem& buffer, bool retainObject = false) : + Buffer(buffer, retainObject) + { + } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + BufferD3D10& operator= (const cl_mem& rhs) + { + Buffer::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + BufferD3D10(const BufferD3D10& buf) : + Buffer(buf) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + BufferD3D10& operator= (const BufferD3D10& buf) + { + Buffer::operator=(buf); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + BufferD3D10(BufferD3D10&& buf) CL_HPP_NOEXCEPT_ : Buffer(std::move(buf)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + BufferD3D10& operator= (BufferD3D10&& buf) + { + Buffer::operator=(std::move(buf)); + + return *this; + } +}; +#endif + +/*! \brief Class interface for GL Buffer Memory Objects. + * + * This is provided to facilitate interoperability with OpenGL. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class BufferGL : public Buffer +{ +public: + /*! \brief Constructs a BufferGL in a specified context, from a given + * GL buffer. + * + * Wraps clCreateFromGLBuffer(). + */ + BufferGL( + const Context& context, + cl_mem_flags flags, + cl_GLuint bufobj, + cl_int* err = NULL) + { + cl_int error; + object_ = ::clCreateFromGLBuffer( + context(), + flags, + bufobj, + &error); + + detail::errHandler(error, __CREATE_GL_BUFFER_ERR); + if(err != NULL) + { + *err = error; + } + } + + //! \brief Default constructor - initializes to NULL. + BufferGL() : Buffer() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * See Memory for further details. + */ + explicit BufferGL(const cl_mem& buffer, bool retainObject = false) : + Buffer(buffer, retainObject) + { + } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + BufferGL& operator= (const cl_mem& rhs) + { + Buffer::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + BufferGL(const BufferGL& buf) : Buffer(buf) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + BufferGL& operator= (const BufferGL& buf) + { + Buffer::operator=(buf); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + BufferGL(BufferGL&& buf) CL_HPP_NOEXCEPT_ : Buffer(std::move(buf)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + BufferGL& operator= (BufferGL&& buf) + { + Buffer::operator=(std::move(buf)); + + return *this; + } + + //! \brief Wrapper for clGetGLObjectInfo(). + cl_int getObjectInfo( + cl_gl_object_type* type, + cl_GLuint* gl_object_name) + { + return detail::errHandler( + ::clGetGLObjectInfo(object_, type, gl_object_name), + __GET_GL_OBJECT_INFO_ERR); + } +}; + +/*! \brief Class interface for GL Render Buffer Memory Objects. + * + * This is provided to facilitate interoperability with OpenGL. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class BufferRenderGL : public Buffer +{ +public: + /*! \brief Constructs a BufferRenderGL in a specified context, from a given + * GL Renderbuffer. + * + * Wraps clCreateFromGLRenderbuffer(). + */ + BufferRenderGL( + const Context& context, + cl_mem_flags flags, + cl_GLuint bufobj, + cl_int* err = NULL) + { + cl_int error; + object_ = ::clCreateFromGLRenderbuffer( + context(), + flags, + bufobj, + &error); + + detail::errHandler(error, __CREATE_GL_RENDER_BUFFER_ERR); + if(err != NULL) + { + *err = error; + } + } + + //! \brief Default constructor - initializes to NULL. + BufferRenderGL() : Buffer() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * See Memory for further details. + */ + explicit BufferRenderGL(const cl_mem& buffer, bool retainObject = false) : + Buffer(buffer, retainObject) + { + } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + BufferRenderGL& operator= (const cl_mem& rhs) + { + Buffer::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + BufferRenderGL(const BufferRenderGL& buf) : Buffer(buf) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + BufferRenderGL& operator= (const BufferRenderGL& buf) + { + Buffer::operator=(buf); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + BufferRenderGL(BufferRenderGL&& buf) CL_HPP_NOEXCEPT_ : Buffer(std::move(buf)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + BufferRenderGL& operator= (BufferRenderGL&& buf) + { + Buffer::operator=(std::move(buf)); + + return *this; + } + + //! \brief Wrapper for clGetGLObjectInfo(). + cl_int getObjectInfo( + cl_gl_object_type* type, + cl_GLuint* gl_object_name) + { + return detail::errHandler( + ::clGetGLObjectInfo(object_, type, gl_object_name), + __GET_GL_OBJECT_INFO_ERR); + } +}; + +/*! \brief C++ base class for Image Memory objects. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class Image : public Memory +{ +protected: + //! \brief Default constructor - initializes to NULL. + Image() : Memory() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * See Memory for further details. + */ + explicit Image(const cl_mem& image, bool retainObject = false) : + Memory(image, retainObject) + { + } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + Image& operator= (const cl_mem& rhs) + { + Memory::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image(const Image& img) : Memory(img) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image& operator= (const Image& img) + { + Memory::operator=(img); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image(Image&& img) CL_HPP_NOEXCEPT_ : Memory(std::move(img)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image& operator= (Image&& img) + { + Memory::operator=(std::move(img)); + + return *this; + } + +public: + //! \brief Wrapper for clGetImageInfo(). + template + cl_int getImageInfo(cl_image_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetImageInfo, object_, name, param), + __GET_IMAGE_INFO_ERR); + } + + //! \brief Wrapper for clGetImageInfo() that returns by value. + template typename + detail::param_traits::param_type getImageInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_image_info, name>::param_type param; + cl_int result = getImageInfo(name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } + + virtual ~Image() + { + } +}; + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + +/*! \brief Class interface for 1D Image Memory objects. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class Image1D : public Image +{ +public: + /*! \brief Constructs a 1D Image in a specified context. + * + * Wraps clCreateImage(). + */ + Image1D( + const Context& context, + cl_mem_flags flags, + ImageFormat format, + size_type width, + void* host_ptr = NULL, + cl_int* err = NULL) + { + cl_int error; + cl_image_desc desc = + { + CL_MEM_OBJECT_IMAGE1D, + width, + 0, 0, 0, 0, 0, 0, 0, 0 + }; + object_ = ::clCreateImage( + context(), + flags, + &format, + &desc, + host_ptr, + &error); + + detail::errHandler(error, __CREATE_IMAGE_ERR); + if(err != NULL) + { + *err = error; + } + } + + //! \brief Default constructor - initializes to NULL. + Image1D() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * See Memory for further details. + */ + explicit Image1D(const cl_mem& image1D, bool retainObject = false) : + Image(image1D, retainObject) + { + } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + Image1D& operator= (const cl_mem& rhs) + { + Image::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image1D(const Image1D& img) : Image(img) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image1D& operator= (const Image1D& img) + { + Image::operator=(img); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image1D(Image1D&& img) CL_HPP_NOEXCEPT_ : Image(std::move(img)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image1D& operator= (Image1D&& img) + { + Image::operator=(std::move(img)); + + return *this; + } +}; + +/*! \class Image1DBuffer + * \brief Image interface for 1D buffer images. + */ +class Image1DBuffer : public Image +{ +public: + Image1DBuffer( + const Context& context, + cl_mem_flags flags, + ImageFormat format, + size_type width, + const Buffer& buffer, + cl_int* err = NULL) + { + cl_int error; + cl_image_desc desc = + { + CL_MEM_OBJECT_IMAGE1D_BUFFER, + width, + 0, 0, 0, 0, 0, 0, 0, + buffer() + }; + object_ = ::clCreateImage( + context(), + flags, + &format, + &desc, + NULL, + &error); + + detail::errHandler(error, __CREATE_IMAGE_ERR); + if(err != NULL) + { + *err = error; + } + } + + Image1DBuffer() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * See Memory for further details. + */ + explicit Image1DBuffer(const cl_mem& image1D, bool retainObject = false) : + Image(image1D, retainObject) + { + } + + Image1DBuffer& operator= (const cl_mem& rhs) + { + Image::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image1DBuffer(const Image1DBuffer& img) : Image(img) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image1DBuffer& operator= (const Image1DBuffer& img) + { + Image::operator=(img); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image1DBuffer(Image1DBuffer&& img) CL_HPP_NOEXCEPT_ : Image(std::move(img)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image1DBuffer& operator= (Image1DBuffer&& img) + { + Image::operator=(std::move(img)); + + return *this; + } +}; + +/*! \class Image1DArray + * \brief Image interface for arrays of 1D images. + */ +class Image1DArray : public Image +{ +public: + Image1DArray( + const Context& context, + cl_mem_flags flags, + ImageFormat format, + size_type arraySize, + size_type width, + size_type rowPitch, + void* host_ptr = NULL, + cl_int* err = NULL) + { + cl_int error; + cl_image_desc desc = + { + CL_MEM_OBJECT_IMAGE1D_ARRAY, + width, + 0, 0, //height, depth (unused) + arraySize, + rowPitch, + 0, 0, 0, 0 + }; + object_ = ::clCreateImage( + context(), + flags, + &format, + &desc, + host_ptr, + &error); + + detail::errHandler(error, __CREATE_IMAGE_ERR); + if(err != NULL) + { + *err = error; + } + } + + Image1DArray() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * See Memory for further details. + */ + explicit Image1DArray(const cl_mem& imageArray, bool retainObject = false) : + Image(imageArray, retainObject) + { + } + + Image1DArray& operator= (const cl_mem& rhs) + { + Image::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image1DArray(const Image1DArray& img) : Image(img) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image1DArray& operator= (const Image1DArray& img) + { + Image::operator=(img); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image1DArray(Image1DArray&& img) CL_HPP_NOEXCEPT_ : Image(std::move(img)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image1DArray& operator= (Image1DArray&& img) + { + Image::operator=(std::move(img)); + + return *this; + } +}; +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + +/*! \brief Class interface for 2D Image Memory objects. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class Image2D : public Image +{ +public: + /*! \brief Constructs a 2D Image in a specified context. + * + * Wraps clCreateImage(). + */ + Image2D( + const Context& context, + cl_mem_flags flags, + ImageFormat format, + size_type width, + size_type height, + size_type row_pitch = 0, + void* host_ptr = NULL, + cl_int* err = NULL) + { + cl_int error; + bool useCreateImage; + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 && CL_HPP_MINIMUM_OPENCL_VERSION < 120 + //Run-time decision based on the actual platform + { + cl_uint version = detail::getContextPlatformVersion(context()); + useCreateImage = (version >= 0x10002); //OpenCL 1.2 or above + } +#elif CL_HPP_TARGET_OPENCL_VERSION >= 120 + useCreateImage = true; +#else + useCreateImage = false; +#endif + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + if(useCreateImage) + { + cl_image_desc desc = + { + CL_MEM_OBJECT_IMAGE2D, + width, + height, + 0, 0, //depth, array size (unused) + row_pitch, + 0, 0, 0, 0 + }; + object_ = ::clCreateImage( + context(), + flags, + &format, + &desc, + host_ptr, + &error); + + detail::errHandler(error, __CREATE_IMAGE_ERR); + if(err != NULL) + { + *err = error; + } + } +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 +#if CL_HPP_MINIMUM_OPENCL_VERSION < 120 + if(!useCreateImage) + { + object_ = ::clCreateImage2D( + context(), flags, &format, width, height, row_pitch, host_ptr, &error); + + detail::errHandler(error, __CREATE_IMAGE2D_ERR); + if(err != NULL) + { + *err = error; + } + } +#endif //CL_HPP_MINIMUM_OPENCL_VERSION < 120 + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + /*! \brief Constructs a 2D Image from a buffer. + * \note This will share storage with the underlying buffer. + * + * Wraps clCreateImage(). + */ + Image2D( + const Context& context, + ImageFormat format, + const Buffer& sourceBuffer, + size_type width, + size_type height, + size_type row_pitch = 0, + cl_int* err = nullptr) + { + cl_int error; + + cl_image_desc desc = + { + CL_MEM_OBJECT_IMAGE2D, + width, + height, + 0, 0, //depth, array size (unused) + row_pitch, + 0, 0, 0, + //Use buffer as input to image + sourceBuffer() + }; + object_ = ::clCreateImage( + context(), + 0, //flags inherited from buffer + &format, + &desc, + nullptr, + &error); + + detail::errHandler(error, __CREATE_IMAGE_ERR); + if(err != nullptr) + { + *err = error; + } + } + +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + /*! \brief Constructs a 2D Image from an image. + * \note This will share storage with the underlying image but may + * reinterpret the channel order and type. + * + * The image will be created matching with a descriptor matching the source. + * + * \param order is the channel order to reinterpret the image data as. + * The channel order may differ as described in the OpenCL + * 2.0 API specification. + * + * Wraps clCreateImage(). + */ + Image2D( + const Context& context, + cl_channel_order order, + const Image& sourceImage, + cl_int* err = nullptr) + { + cl_int error; + + //Descriptor fields have to match source image + size_type sourceWidth = + sourceImage.getImageInfo(); + size_type sourceHeight = + sourceImage.getImageInfo(); + size_type sourceRowPitch = + sourceImage.getImageInfo(); + cl_uint sourceNumMIPLevels = + sourceImage.getImageInfo(); + cl_uint sourceNumSamples = + sourceImage.getImageInfo(); + cl_image_format sourceFormat = + sourceImage.getImageInfo(); + + //Update only the channel order. + //Channel format inherited from source. + sourceFormat.image_channel_order = order; + cl_image_desc desc = + { + CL_MEM_OBJECT_IMAGE2D, + sourceWidth, + sourceHeight, + 0, 0, //depth (unused), array size (unused) + sourceRowPitch, + 0, //slice pitch (unused) + sourceNumMIPLevels, + sourceNumSamples, + //Use buffer as input to image + sourceImage() + }; + object_ = ::clCreateImage( + context(), + 0, //flags should be inherited from mem_object + &sourceFormat, + &desc, + nullptr, + &error); + + detail::errHandler(error, __CREATE_IMAGE_ERR); + if(err != nullptr) + { + *err = error; + } + } + +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + + //! \brief Default constructor - initializes to NULL. + Image2D() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * See Memory for further details. + */ + explicit Image2D(const cl_mem& image2D, bool retainObject = false) : + Image(image2D, retainObject) + { + } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + Image2D& operator= (const cl_mem& rhs) + { + Image::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image2D(const Image2D& img) : Image(img) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image2D& operator= (const Image2D& img) + { + Image::operator=(img); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image2D(Image2D&& img) CL_HPP_NOEXCEPT_ : Image(std::move(img)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image2D& operator= (Image2D&& img) + { + Image::operator=(std::move(img)); + + return *this; + } +}; + +#if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + +/*! \brief Class interface for GL 2D Image Memory objects. + * + * This is provided to facilitate interoperability with OpenGL. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + * \note Deprecated for OpenCL 1.2. Please use ImageGL instead. + */ +class CL_EXT_PREFIX__VERSION_1_1_DEPRECATED Image2DGL : public Image2D +{ +public: + /*! \brief Constructs an Image2DGL in a specified context, from a given + * GL Texture. + * + * Wraps clCreateFromGLTexture2D(). + */ + Image2DGL( + const Context& context, + cl_mem_flags flags, + cl_GLenum target, + cl_GLint miplevel, + cl_GLuint texobj, + cl_int* err = NULL) + { + cl_int error; + object_ = ::clCreateFromGLTexture2D( + context(), + flags, + target, + miplevel, + texobj, + &error); + + detail::errHandler(error, __CREATE_GL_TEXTURE_2D_ERR); + if(err != NULL) + { + *err = error; + } + } + + //! \brief Default constructor - initializes to NULL. + Image2DGL() : Image2D() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * See Memory for further details. + */ + explicit Image2DGL(const cl_mem& image, bool retainObject = false) : + Image2D(image, retainObject) + { + } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * c + * See Memory for further details. + */ + Image2DGL& operator= (const cl_mem& rhs) + { + Image2D::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image2DGL(const Image2DGL& img) : Image2D(img) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image2DGL& operator= (const Image2DGL& img) + { + Image2D::operator=(img); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image2DGL(Image2DGL&& img) CL_HPP_NOEXCEPT_ : Image2D(std::move(img)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image2DGL& operator= (Image2DGL&& img) + { + Image2D::operator=(std::move(img)); + + return *this; + } +} + +CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; +#endif //CL_USE_DEPRECATED_OPENCL_1_1_APIS + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + +/*! \class Image2DArray + * \brief Image interface for arrays of 2D images. + */ +class Image2DArray : public Image +{ +public: + Image2DArray( + const Context& context, + cl_mem_flags flags, + ImageFormat format, + size_type arraySize, + size_type width, + size_type height, + size_type rowPitch, + size_type slicePitch, + void* host_ptr = NULL, + cl_int* err = NULL) + { + cl_int error; + cl_image_desc desc = + { + CL_MEM_OBJECT_IMAGE2D_ARRAY, + width, + height, + 0, //depth (unused) + arraySize, + rowPitch, + slicePitch, + 0, 0, 0 + }; + object_ = ::clCreateImage( + context(), + flags, + &format, + &desc, + host_ptr, + &error); + + detail::errHandler(error, __CREATE_IMAGE_ERR); + if(err != NULL) + { + *err = error; + } + } + + Image2DArray() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * See Memory for further details. + */ + explicit Image2DArray(const cl_mem& imageArray, bool retainObject = false) : Image(imageArray, + retainObject) + { + } + + Image2DArray& operator= (const cl_mem& rhs) + { + Image::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image2DArray(const Image2DArray& img) : Image(img) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image2DArray& operator= (const Image2DArray& img) + { + Image::operator=(img); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image2DArray(Image2DArray&& img) CL_HPP_NOEXCEPT_ : Image(std::move(img)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image2DArray& operator= (Image2DArray&& img) + { + Image::operator=(std::move(img)); + + return *this; + } +}; +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + +/*! \brief Class interface for 3D Image Memory objects. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class Image3D : public Image +{ +public: + /*! \brief Constructs a 3D Image in a specified context. + * + * Wraps clCreateImage(). + */ + Image3D( + const Context& context, + cl_mem_flags flags, + ImageFormat format, + size_type width, + size_type height, + size_type depth, + size_type row_pitch = 0, + size_type slice_pitch = 0, + void* host_ptr = NULL, + cl_int* err = NULL) + { + cl_int error; + bool useCreateImage; + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 && CL_HPP_MINIMUM_OPENCL_VERSION < 120 + //Run-time decision based on the actual platform + { + cl_uint version = detail::getContextPlatformVersion(context()); + useCreateImage = (version >= 0x10002); //OpenCL 1.2 or above + } +#elif CL_HPP_TARGET_OPENCL_VERSION >= 120 + useCreateImage = true; +#else + useCreateImage = false; +#endif + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + if(useCreateImage) + { + cl_image_desc desc = + { + CL_MEM_OBJECT_IMAGE3D, + width, + height, + depth, + 0, //array size (unused) + row_pitch, + slice_pitch, + 0, 0, 0 + }; + object_ = ::clCreateImage( + context(), + flags, + &format, + &desc, + host_ptr, + &error); + + detail::errHandler(error, __CREATE_IMAGE_ERR); + if(err != NULL) + { + *err = error; + } + } +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 +#if CL_HPP_MINIMUM_OPENCL_VERSION < 120 + if(!useCreateImage) + { + object_ = ::clCreateImage3D( + context(), flags, &format, width, height, depth, row_pitch, + slice_pitch, host_ptr, &error); + + detail::errHandler(error, __CREATE_IMAGE3D_ERR); + if(err != NULL) + { + *err = error; + } + } +#endif //CL_HPP_MINIMUM_OPENCL_VERSION < 120 + } + + //! \brief Default constructor - initializes to NULL. + Image3D() : Image() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * See Memory for further details. + */ + explicit Image3D(const cl_mem& image3D, bool retainObject = false) : + Image(image3D, retainObject) + { + } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + Image3D& operator= (const cl_mem& rhs) + { + Image::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image3D(const Image3D& img) : Image(img) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image3D& operator= (const Image3D& img) + { + Image::operator=(img); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image3D(Image3D&& img) CL_HPP_NOEXCEPT_ : Image(std::move(img)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image3D& operator= (Image3D&& img) + { + Image::operator=(std::move(img)); + + return *this; + } +}; + +#if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + +/*! \brief Class interface for GL 3D Image Memory objects. + * + * This is provided to facilitate interoperability with OpenGL. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class Image3DGL : public Image3D +{ +public: + /*! \brief Constructs an Image3DGL in a specified context, from a given + * GL Texture. + * + * Wraps clCreateFromGLTexture3D(). + */ + Image3DGL( + const Context& context, + cl_mem_flags flags, + cl_GLenum target, + cl_GLint miplevel, + cl_GLuint texobj, + cl_int* err = NULL) + { + cl_int error; + object_ = ::clCreateFromGLTexture3D( + context(), + flags, + target, + miplevel, + texobj, + &error); + + detail::errHandler(error, __CREATE_GL_TEXTURE_3D_ERR); + if(err != NULL) + { + *err = error; + } + } + + //! \brief Default constructor - initializes to NULL. + Image3DGL() : Image3D() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * See Memory for further details. + */ + explicit Image3DGL(const cl_mem& image, bool retainObject = false) : + Image3D(image, retainObject) + { + } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + Image3DGL& operator= (const cl_mem& rhs) + { + Image3D::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image3DGL(const Image3DGL& img) : Image3D(img) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Image3DGL& operator= (const Image3DGL& img) + { + Image3D::operator=(img); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Image3DGL(Image3DGL&& img) CL_HPP_NOEXCEPT_ : Image3D(std::move(img)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Image3DGL& operator= (Image3DGL&& img) + { + Image3D::operator=(std::move(img)); + + return *this; + } +}; +#endif //CL_USE_DEPRECATED_OPENCL_1_1_APIS + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + +/*! \class ImageGL + * \brief general image interface for GL interop. + * We abstract the 2D and 3D GL images into a single instance here + * that wraps all GL sourced images on the grounds that setup information + * was performed by OpenCL anyway. + */ +class ImageGL : public Image +{ +public: + ImageGL( + const Context& context, + cl_mem_flags flags, + cl_GLenum target, + cl_GLint miplevel, + cl_GLuint texobj, + cl_int* err = NULL) + { + cl_int error; + object_ = ::clCreateFromGLTexture( + context(), + flags, + target, + miplevel, + texobj, + &error); + + detail::errHandler(error, __CREATE_GL_TEXTURE_ERR); + if(err != NULL) + { + *err = error; + } + } + + ImageGL() : Image() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * See Memory for further details. + */ + explicit ImageGL(const cl_mem& image, bool retainObject = false) : + Image(image, retainObject) + { + } + + ImageGL& operator= (const cl_mem& rhs) + { + Image::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + ImageGL(const ImageGL& img) : Image(img) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + ImageGL& operator= (const ImageGL& img) + { + Image::operator=(img); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + ImageGL(ImageGL&& img) CL_HPP_NOEXCEPT_ : Image(std::move(img)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + ImageGL& operator= (ImageGL&& img) + { + Image::operator=(std::move(img)); + + return *this; + } +}; +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + +/*! \brief Class interface for Pipe Memory Objects. + * + * See Memory for details about copy semantics, etc. + * + * \see Memory + */ +class Pipe : public Memory +{ +public: + /*! \brief Constructs a Pipe in a specified context. + * + * Wraps clCreatePipe(). + * @param context Context in which to create the pipe. + * @param flags Bitfield. Only CL_MEM_READ_WRITE and CL_MEM_HOST_NO_ACCESS are valid. + * @param packet_size Size in bytes of a single packet of the pipe. + * @param max_packets Number of packets that may be stored in the pipe. + * + */ + Pipe( + const Context& context, + cl_uint packet_size, + cl_uint max_packets, + cl_int* err = NULL) + { + cl_int error; + + cl_mem_flags flags = CL_MEM_READ_WRITE | CL_MEM_HOST_NO_ACCESS; + object_ = ::clCreatePipe(context(), flags, packet_size, max_packets, nullptr, &error); + + detail::errHandler(error, __CREATE_PIPE_ERR); + if(err != NULL) + { + *err = error; + } + } + + /*! \brief Constructs a Pipe in a the default context. + * + * Wraps clCreatePipe(). + * @param flags Bitfield. Only CL_MEM_READ_WRITE and CL_MEM_HOST_NO_ACCESS are valid. + * @param packet_size Size in bytes of a single packet of the pipe. + * @param max_packets Number of packets that may be stored in the pipe. + * + */ + Pipe( + cl_uint packet_size, + cl_uint max_packets, + cl_int* err = NULL) + { + cl_int error; + + Context context = Context::getDefault(err); + + cl_mem_flags flags = CL_MEM_READ_WRITE | CL_MEM_HOST_NO_ACCESS; + object_ = ::clCreatePipe(context(), flags, packet_size, max_packets, nullptr, &error); + + detail::errHandler(error, __CREATE_PIPE_ERR); + if(err != NULL) + { + *err = error; + } + } + + //! \brief Default constructor - initializes to NULL. + Pipe() : Memory() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with earlier versions. + * + * See Memory for further details. + */ + explicit Pipe(const cl_mem& pipe, bool retainObject = false) : + Memory(pipe, retainObject) + { + } + + /*! \brief Assignment from cl_mem - performs shallow copy. + * + * See Memory for further details. + */ + Pipe& operator= (const cl_mem& rhs) + { + Memory::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Pipe(const Pipe& pipe) : Memory(pipe) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Pipe& operator= (const Pipe& pipe) + { + Memory::operator=(pipe); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Pipe(Pipe&& pipe) CL_HPP_NOEXCEPT_ : Memory(std::move(pipe)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Pipe& operator= (Pipe&& pipe) + { + Memory::operator=(std::move(pipe)); + + return *this; + } + + //! \brief Wrapper for clGetMemObjectInfo(). + template + cl_int getInfo(cl_pipe_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetPipeInfo, object_, name, param), + __GET_PIPE_INFO_ERR); + } + + //! \brief Wrapper for clGetMemObjectInfo() that returns by value. + template typename + detail::param_traits::param_type getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_pipe_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } +}; //class Pipe +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 200 + +/*! \brief Class interface for cl_sampler. + * + * \note Copies of these objects are shallow, meaning that the copy will refer + * to the same underlying cl_sampler as the original. For details, see + * clRetainSampler() and clReleaseSampler(). + * + * \see cl_sampler + */ +class Sampler : public detail::Wrapper +{ +public: + //! \brief Default constructor - initializes to NULL. + Sampler() + { + } + + /*! \brief Constructs a Sampler in a specified context. + * + * Wraps clCreateSampler(). + */ + Sampler( + const Context& context, + cl_bool normalized_coords, + cl_addressing_mode addressing_mode, + cl_filter_mode filter_mode, + cl_int* err = NULL) + { + cl_int error; + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + cl_sampler_properties sampler_properties[] = { + CL_SAMPLER_NORMALIZED_COORDS, normalized_coords, + CL_SAMPLER_ADDRESSING_MODE, addressing_mode, + CL_SAMPLER_FILTER_MODE, filter_mode, + 0 }; + object_ = ::clCreateSamplerWithProperties( + context(), + sampler_properties, + &error); + + detail::errHandler(error, __CREATE_SAMPLER_WITH_PROPERTIES_ERR); + if(err != NULL) + { + *err = error; + } +#else + object_ = ::clCreateSampler( + context(), + normalized_coords, + addressing_mode, + filter_mode, + &error); + + detail::errHandler(error, __CREATE_SAMPLER_ERR); + if(err != NULL) + { + *err = error; + } +#endif + } + + /*! \brief Constructor from cl_sampler - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * This effectively transfers ownership of a refcount on the cl_sampler + * into the new Sampler object. + */ + explicit Sampler(const cl_sampler& sampler, bool retainObject = false) : + detail::Wrapper(sampler, retainObject) + { + } + + /*! \brief Assignment operator from cl_sampler - takes ownership. + * + * This effectively transfers ownership of a refcount on the rhs and calls + * clReleaseSampler() on the value previously held by this instance. + */ + Sampler& operator= (const cl_sampler& rhs) + { + detail::Wrapper::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Sampler(const Sampler& sam) : detail::Wrapper(sam) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Sampler& operator= (const Sampler& sam) + { + detail::Wrapper::operator=(sam); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Sampler(Sampler&& sam) CL_HPP_NOEXCEPT_ : detail::Wrapper(std::move(sam)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Sampler& operator= (Sampler&& sam) + { + detail::Wrapper::operator=(std::move(sam)); + + return *this; + } + + //! \brief Wrapper for clGetSamplerInfo(). + template + cl_int getInfo(cl_sampler_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetSamplerInfo, object_, name, param), + __GET_SAMPLER_INFO_ERR); + } + + //! \brief Wrapper for clGetSamplerInfo() that returns by value. + template typename + detail::param_traits::param_type getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_sampler_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } +}; + +class Program; + +class CommandQueue; + +class DeviceCommandQueue; + +class Kernel; + +//! \brief Class interface for specifying NDRange values. +class NDRange +{ +private: + size_type sizes_[3]; + cl_uint dimensions_; + +public: + //! \brief Default constructor - resulting range has zero dimensions. + NDRange() + : dimensions_(0) + { + sizes_[0] = 0; + sizes_[1] = 0; + sizes_[2] = 0; + } + + //! \brief Constructs one-dimensional range. + NDRange(size_type size0) + : dimensions_(1) + { + sizes_[0] = size0; + sizes_[1] = 1; + sizes_[2] = 1; + } + + //! \brief Constructs two-dimensional range. + NDRange(size_type size0, size_type size1) + : dimensions_(2) + { + sizes_[0] = size0; + sizes_[1] = size1; + sizes_[2] = 1; + } + + //! \brief Constructs three-dimensional range. + NDRange(size_type size0, size_type size1, size_type size2) + : dimensions_(3) + { + sizes_[0] = size0; + sizes_[1] = size1; + sizes_[2] = size2; + } + + /*! \brief Conversion operator to const size_type *. + * + * \returns a pointer to the size of the first dimension. + */ + operator const size_type*() const { + return sizes_; + } + + //! \brief Queries the number of dimensions in the range. + size_type dimensions() const + { + return dimensions_; + } + + //! \brief Returns the size of the object in bytes based on the + //runtime number of dimensions + size_type size() const + { + return dimensions_ * sizeof(size_type); + } + + size_type* get() + { + return sizes_; + } + + const size_type* get() const + { + return sizes_; + } +}; + +//! \brief A zero-dimensional range. +static const NDRange NullRange; + +//! \brief Local address wrapper for use with Kernel::setArg +struct LocalSpaceArg +{ + size_type size_; +}; + +namespace detail { +template +struct KernelArgumentHandler; + +//Enable for objects that are not subclasses of memory +//Pointers, constants etc +template +struct KernelArgumentHandler::value>::type> +{ + static size_type size(const T&) { + return sizeof(T); + } + + static const T* ptr(const T& value) { + return &value; + } +}; + +//Enable for subclasses of memory where we want to get a reference to the cl_mem out +//and pass that in for safety +template +struct KernelArgumentHandler::value>::type> +{ + static size_type size(const T&) { + return sizeof(cl_mem); + } + + static const cl_mem* ptr(const T& value) { + return &(value()); + } +}; + +//Specialization for DeviceCommandQueue defined later + +template<> +struct KernelArgumentHandler +{ + static size_type size(const LocalSpaceArg& value) { + return value.size_; + } + + static const void* ptr(const LocalSpaceArg&) { + return NULL; + } +}; +} +//! \endcond + +/*! Local + * \brief Helper function for generating LocalSpaceArg objects. + */ +inline LocalSpaceArg Local(size_type size) +{ + LocalSpaceArg ret = { size }; + + return ret; +} + +/*! \brief Class interface for cl_kernel. + * + * \note Copies of these objects are shallow, meaning that the copy will refer + * to the same underlying cl_kernel as the original. For details, see + * clRetainKernel() and clReleaseKernel(). + * + * \see cl_kernel + */ +class Kernel : public detail::Wrapper +{ +public: + inline Kernel(const Program& program, const char* name, cl_int* err = NULL); + + //! \brief Default constructor - initializes to NULL. + Kernel() + { + } + + /*! \brief Constructor from cl_kernel - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + * This effectively transfers ownership of a refcount on the cl_kernel + * into the new Kernel object. + */ + explicit Kernel(const cl_kernel& kernel, bool retainObject = false) : + detail::Wrapper(kernel, retainObject) + { + } + + /*! \brief Assignment operator from cl_kernel - takes ownership. + * + * This effectively transfers ownership of a refcount on the rhs and calls + * clReleaseKernel() on the value previously held by this instance. + */ + Kernel& operator= (const cl_kernel& rhs) + { + detail::Wrapper::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Kernel(const Kernel& kernel) : detail::Wrapper(kernel) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Kernel& operator= (const Kernel& kernel) + { + detail::Wrapper::operator=(kernel); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Kernel(Kernel&& kernel) CL_HPP_NOEXCEPT_ : detail::Wrapper(std::move(kernel)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Kernel& operator= (Kernel&& kernel) + { + detail::Wrapper::operator=(std::move(kernel)); + + return *this; + } + + template + cl_int getInfo(cl_kernel_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetKernelInfo, object_, name, param), + __GET_KERNEL_INFO_ERR); + } + + template typename + detail::param_traits::param_type getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_kernel_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + template + cl_int getArgInfo(cl_uint argIndex, cl_kernel_arg_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetKernelArgInfo, object_, argIndex, name, param), + __GET_KERNEL_ARG_INFO_ERR); + } + + template typename + detail::param_traits::param_type getArgInfo(cl_uint argIndex, + cl_int* err = NULL) + const + { + typename detail::param_traits< + detail::cl_kernel_arg_info, name>::param_type param; + cl_int result = getArgInfo(argIndex, name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } + +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 + + template + cl_int getWorkGroupInfo( + const Device& device, cl_kernel_work_group_info name, T* param) const + { + return detail::errHandler( + detail::getInfo( + &::clGetKernelWorkGroupInfo, object_, device(), name, param), + __GET_KERNEL_WORK_GROUP_INFO_ERR); + } + + template typename + detail::param_traits::param_type getWorkGroupInfo( + const Device& device, + cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_kernel_work_group_info, name>::param_type param; + cl_int result = getWorkGroupInfo(device, name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 +#if defined(CL_HPP_USE_CL_SUB_GROUPS_KHR) + cl_int getSubGroupInfo(const cl::Device& dev, + cl_kernel_sub_group_info name, + const cl::NDRange& range, + size_type* param) const + { + typedef clGetKernelSubGroupInfoKHR_fn PFN_clGetKernelSubGroupInfoKHR; + static PFN_clGetKernelSubGroupInfoKHR pfn_clGetKernelSubGroupInfoKHR = NULL; + CL_HPP_INIT_CL_EXT_FCN_PTR_(clGetKernelSubGroupInfoKHR); + + return detail::errHandler( + pfn_clGetKernelSubGroupInfoKHR(object_, dev(), name, range.size(), range.get(), + sizeof(size_type), param, nullptr), + __GET_KERNEL_ARG_INFO_ERR); + } + + template + size_type getSubGroupInfo(const cl::Device& dev, const cl::NDRange& range, + cl_int* err = NULL) const + { + size_type param; + cl_int result = getSubGroupInfo(dev, name, range, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } + +#endif //#if defined(CL_HPP_USE_CL_SUB_GROUPS_KHR) +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + /*! \brief setArg overload taking a shared_ptr type + */ + template + cl_int setArg(cl_uint index, const cl::pointer& argPtr) + { + return detail::errHandler( + ::clSetKernelArgSVMPointer(object_, index, argPtr.get()), + __SET_KERNEL_ARGS_ERR); + } + + /*! \brief setArg overload taking a vector type. + */ + template + cl_int setArg(cl_uint index, const cl::vector& argPtr) + { + return detail::errHandler( + ::clSetKernelArgSVMPointer(object_, index, argPtr.data()), + __SET_KERNEL_ARGS_ERR); + } + + /*! \brief setArg overload taking a pointer type + */ + template + typename std::enable_if::value, cl_int>::type setArg(cl_uint index, + const T argPtr) + { + return detail::errHandler( + ::clSetKernelArgSVMPointer(object_, index, argPtr), + __SET_KERNEL_ARGS_ERR); + } + +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + + /*! \brief setArg overload taking a POD type + */ + template + typename std::enable_if::value, cl_int>::type setArg(cl_uint index, + const T& value) + { + return detail::errHandler( + ::clSetKernelArg( + object_, + index, + detail::KernelArgumentHandler::size(value), + detail::KernelArgumentHandler::ptr(value)), + __SET_KERNEL_ARGS_ERR); + } + + cl_int setArg(cl_uint index, size_type size, const void* argPtr) + { + return detail::errHandler( + ::clSetKernelArg(object_, index, size, argPtr), + __SET_KERNEL_ARGS_ERR); + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + /*! + * Specify a vector of SVM pointers that the kernel may access in + * addition to its arguments. + */ + cl_int setSVMPointers(const vector& pointerList) + { + return detail::errHandler( + ::clSetKernelExecInfo( + object_, + CL_KERNEL_EXEC_INFO_SVM_PTRS, + sizeof(void*) * pointerList.size(), + pointerList.data())); + } + + /*! + * Specify a std::array of SVM pointers that the kernel may access in + * addition to its arguments. + */ + template + cl_int setSVMPointers(const std::array& pointerList) + { + return detail::errHandler( + ::clSetKernelExecInfo( + object_, + CL_KERNEL_EXEC_INFO_SVM_PTRS, + sizeof(void*) * pointerList.size(), + pointerList.data())); + } + + /*! \brief Enable fine-grained system SVM. + * + * \note It is only possible to enable fine-grained system SVM if all devices + * in the context associated with kernel support it. + * + * \param svmEnabled True if fine-grained system SVM is requested. False otherwise. + * \return CL_SUCCESS if the function was executed succesfully. CL_INVALID_OPERATION + * if no devices in the context support fine-grained system SVM. + * + * \see clSetKernelExecInfo + */ + cl_int enableFineGrainedSystemSVM(bool svmEnabled) + { + cl_bool svmEnabled_ = svmEnabled ? CL_TRUE : CL_FALSE; + + return detail::errHandler( + ::clSetKernelExecInfo( + object_, + CL_KERNEL_EXEC_INFO_SVM_FINE_GRAIN_SYSTEM, + sizeof(cl_bool), + &svmEnabled_ + ) + ); + } + + template + void setSVMPointersHelper(std::array& pointerList, + const pointer& t0, + Ts... ts) + { + pointerList[index] = static_cast(t0.get()); + setSVMPointersHelper(ts ...); + } + + template + typename std::enable_if::value, void>::type setSVMPointersHelper( + std::array& pointerList, T0 t0, Ts... ts) + { + pointerList[index] = static_cast(t0); + setSVMPointersHelper(ts ...); + } + + template + void setSVMPointersHelper(std::array& pointerList, const pointer& t0) + { + pointerList[index] = static_cast(t0.get()); + } + + template + typename std::enable_if::value, void>::type setSVMPointersHelper( + std::array& pointerList, T0 t0) + { + pointerList[index] = static_cast(t0); + } + + template + cl_int setSVMPointers(const T0& t0, Ts... ts) + { + std::array pointerList; + + setSVMPointersHelper<0, 1 + sizeof...(Ts)>(pointerList, t0, ts ...); + + return detail::errHandler( + ::clSetKernelExecInfo( + object_, + CL_KERNEL_EXEC_INFO_SVM_PTRS, + sizeof(void*) * (1 + sizeof...(Ts)), + pointerList.data())); + } + +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 200 +}; + +/*! \class Program + * \brief Program interface that implements cl_program. + */ +class Program : public detail::Wrapper +{ +public: +#if !defined(CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY) + typedef vector > Binaries; + typedef vector Sources; +#else //#if !defined(CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY) + typedef vector > Binaries; + typedef vector > Sources; +#endif //#if !defined(CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY) + + Program( + const string& source, + bool build = false, + cl_int* err = NULL) + { + cl_int error; + + const char* strings = source.c_str(); + const size_type length = source.size(); + + Context context = Context::getDefault(err); + + object_ = ::clCreateProgramWithSource( + context(), (cl_uint)1, &strings, &length, &error); + + detail::errHandler(error, __CREATE_PROGRAM_WITH_SOURCE_ERR); + + if(error == CL_SUCCESS && build) + { + error = ::clBuildProgram( + object_, + 0, + NULL, +#if !defined(CL_HPP_CL_1_2_DEFAULT_BUILD) + "-cl-std=CL2.0", +#else + "", +#endif //#if !defined(CL_HPP_CL_1_2_DEFAULT_BUILD) + NULL, + NULL); + + detail::buildErrHandler(error, __BUILD_PROGRAM_ERR, + getBuildInfo()); + } + + if(err != NULL) + { + *err = error; + } + } + + Program( + const Context& context, + const string& source, + bool build = false, + cl_int* err = NULL) + { + cl_int error; + + const char* strings = source.c_str(); + const size_type length = source.size(); + + object_ = ::clCreateProgramWithSource( + context(), (cl_uint)1, &strings, &length, &error); + + detail::errHandler(error, __CREATE_PROGRAM_WITH_SOURCE_ERR); + + if(error == CL_SUCCESS && build) + { + error = ::clBuildProgram( + object_, + 0, + NULL, +#if !defined(CL_HPP_CL_1_2_DEFAULT_BUILD) + "-cl-std=CL2.0", +#else + "", +#endif //#if !defined(CL_HPP_CL_1_2_DEFAULT_BUILD) + NULL, + NULL); + + detail::buildErrHandler(error, __BUILD_PROGRAM_ERR, + getBuildInfo()); + } + + if(err != NULL) + { + *err = error; + } + } + + /** + * Create a program from a vector of source strings and the default context. + * Does not compile or link the program. + */ + Program( + const Sources& sources, + cl_int* err = NULL) + { + cl_int error; + Context context = Context::getDefault(err); + + const size_type n = (size_type)sources.size(); + + vector lengths(n); + vector strings(n); + + for(size_type i = 0; i < n; ++i) + { +#if !defined(CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY) + strings[i] = sources[(int)i].data(); + lengths[i] = sources[(int)i].length(); +#else //#if !defined(CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY) + strings[i] = sources[(int)i].first; + lengths[i] = sources[(int)i].second; +#endif //#if !defined(CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY) + } + + object_ = ::clCreateProgramWithSource( + context(), (cl_uint)n, strings.data(), lengths.data(), &error); + + detail::errHandler(error, __CREATE_PROGRAM_WITH_SOURCE_ERR); + if(err != NULL) + { + *err = error; + } + } + + /** + * Create a program from a vector of source strings and a provided context. + * Does not compile or link the program. + */ + Program( + const Context& context, + const Sources& sources, + cl_int* err = NULL) + { + cl_int error; + + const size_type n = (size_type)sources.size(); + + vector lengths(n); + vector strings(n); + + for(size_type i = 0; i < n; ++i) + { +#if !defined(CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY) + strings[i] = sources[(int)i].data(); + lengths[i] = sources[(int)i].length(); +#else //#if !defined(CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY) + strings[i] = sources[(int)i].first; + lengths[i] = sources[(int)i].second; +#endif //#if !defined(CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY) + } + + object_ = ::clCreateProgramWithSource( + context(), (cl_uint)n, strings.data(), lengths.data(), &error); + + detail::errHandler(error, __CREATE_PROGRAM_WITH_SOURCE_ERR); + if(err != NULL) + { + *err = error; + } + } + + /** + * Construct a program object from a list of devices and a per-device list of binaries. + * \param context A valid OpenCL context in which to construct the program. + * \param devices A vector of OpenCL device objects for which the program will be created. + * \param binaries A vector of pairs of a pointer to a binary object and its length. + * \param binaryStatus An optional vector that on completion will be resized to + * match the size of binaries and filled with values to specify if each binary + * was successfully loaded. + * Set to CL_SUCCESS if the binary was successfully loaded. + * Set to CL_INVALID_VALUE if the length is 0 or the binary pointer is NULL. + * Set to CL_INVALID_BINARY if the binary provided is not valid for the matching device. + * \param err if non-NULL will be set to CL_SUCCESS on successful operation or one of the + *following errors: + * CL_INVALID_CONTEXT if context is not a valid context. + * CL_INVALID_VALUE if the length of devices is zero; or if the length of binaries does not + *match the length of devices; + * or if any entry in binaries is NULL or has length 0. + * CL_INVALID_DEVICE if OpenCL devices listed in devices are not in the list of devices + *associated with context. + * CL_INVALID_BINARY if an invalid program binary was encountered for any device. binaryStatus + *will return specific status for each device. + * CL_OUT_OF_HOST_MEMORY if there is a failure to allocate resources required by the OpenCL + *implementation on the host. + */ + Program( + const Context& context, + const vector& devices, + const Binaries& binaries, + vector* binaryStatus = NULL, + cl_int* err = NULL) + { + cl_int error; + + const size_type numDevices = devices.size(); + + //Catch size mismatch early and return + if(binaries.size() != numDevices) + { + error = CL_INVALID_VALUE; + detail::errHandler(error, __CREATE_PROGRAM_WITH_BINARY_ERR); + if(err != NULL) + { + *err = error; + } + + return; + } + + vector lengths(numDevices); + vector images(numDevices); +#if !defined(CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY) + for(size_type i = 0; i < numDevices; ++i) + { + images[i] = binaries[i].data(); + lengths[i] = binaries[(int)i].size(); + } +#else //#if !defined(CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY) + for(size_type i = 0; i < numDevices; ++i) + { + images[i] = (const unsigned char*)binaries[i].first; + lengths[i] = binaries[(int)i].second; + } +#endif //#if !defined(CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY) + + vector deviceIDs(numDevices); + for(size_type deviceIndex = 0; deviceIndex < numDevices; ++deviceIndex) + { + deviceIDs[deviceIndex] = (devices[deviceIndex])(); + } + + if(binaryStatus) + { + binaryStatus->resize(numDevices); + } + + object_ = ::clCreateProgramWithBinary( + context(), (cl_uint)devices.size(), + deviceIDs.data(), + lengths.data(), images.data(), (binaryStatus != NULL && numDevices > 0) + ? &binaryStatus->front() + : NULL, &error); + + detail::errHandler(error, __CREATE_PROGRAM_WITH_BINARY_ERR); + if(err != NULL) + { + *err = error; + } + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + /** + * Create program using builtin kernels. + * \param kernelNames Semi-colon separated list of builtin kernel names + */ + Program( + const Context& context, + const vector& devices, + const string& kernelNames, + cl_int* err = NULL) + { + cl_int error; + + size_type numDevices = devices.size(); + vector deviceIDs(numDevices); + for(size_type deviceIndex = 0; deviceIndex < numDevices; ++deviceIndex) + { + deviceIDs[deviceIndex] = (devices[deviceIndex])(); + } + + object_ = ::clCreateProgramWithBuiltInKernels( + context(), + (cl_uint)devices.size(), + deviceIDs.data(), + kernelNames.c_str(), + &error); + + detail::errHandler(error, __CREATE_PROGRAM_WITH_BUILT_IN_KERNELS_ERR); + if(err != NULL) + { + *err = error; + } + } + +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 + + Program() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + */ + explicit Program(const cl_program& program, bool retainObject = false) : + detail::Wrapper(program, retainObject) + { + } + + Program& operator= (const cl_program& rhs) + { + detail::Wrapper::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + Program(const Program& program) : detail::Wrapper(program) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + Program& operator= (const Program& program) + { + detail::Wrapper::operator=(program); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + Program(Program&& program) CL_HPP_NOEXCEPT_ : detail::Wrapper(std::move(program)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + Program& operator= (Program&& program) + { + detail::Wrapper::operator=(std::move(program)); + + return *this; + } + + cl_int build( + const vector& devices, + const char* options = NULL, + void(CL_CALLBACK* notifyFptr)(cl_program, void*) = NULL, + void* data = NULL) const + { + size_type numDevices = devices.size(); + vector deviceIDs(numDevices); + + for(size_type deviceIndex = 0; deviceIndex < numDevices; ++deviceIndex) + { + deviceIDs[deviceIndex] = (devices[deviceIndex])(); + } + + cl_int buildError = ::clBuildProgram( + object_, + (cl_uint) + devices.size(), + deviceIDs.data(), + options, + notifyFptr, + data); + + return detail::buildErrHandler(buildError, __BUILD_PROGRAM_ERR, + getBuildInfo()); + } + + cl_int build( + const char* options = NULL, + void(CL_CALLBACK* notifyFptr)(cl_program, void*) = NULL, + void* data = NULL) const + { + cl_int buildError = ::clBuildProgram( + object_, + 0, + NULL, + options, + notifyFptr, + data); + + return detail::buildErrHandler(buildError, __BUILD_PROGRAM_ERR, + getBuildInfo()); + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + cl_int compile( + const char* options = NULL, + void(CL_CALLBACK* notifyFptr)(cl_program, void*) = NULL, + void* data = NULL) const + { + cl_int error = ::clCompileProgram( + object_, + 0, + NULL, + options, + 0, + NULL, + NULL, + notifyFptr, + data); + + return detail::buildErrHandler(error, __COMPILE_PROGRAM_ERR, + getBuildInfo()); + } + +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 + + template + cl_int getInfo(cl_program_info name, T* param) const + { + return detail::errHandler( + detail::getInfo(&::clGetProgramInfo, object_, name, param), + __GET_PROGRAM_INFO_ERR); + } + + template typename + detail::param_traits::param_type getInfo(cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_program_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } + + template + cl_int getBuildInfo( + const Device& device, cl_program_build_info name, T* param) const + { + return detail::errHandler( + detail::getInfo( + &::clGetProgramBuildInfo, object_, device(), name, param), + __GET_PROGRAM_BUILD_INFO_ERR); + } + + template typename + detail::param_traits::param_type getBuildInfo( + const Device& device, + cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_program_build_info, name>::param_type param; + cl_int result = getBuildInfo(device, name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } + + /** + * Build info function that returns a vector of device/info pairs for the specified + * info type and for all devices in the program. + * On an error reading the info for any device, an empty vector of info will be returned. + */ + template + vector::param_type> > getBuildInfo( + cl_int* err = NULL) const + { + cl_int result = CL_SUCCESS; + + auto devs = getInfo(&result); + vector::param_type> > + devInfo; + + //If there was an initial error from getInfo return the error + if(result != CL_SUCCESS) + { + if(err != NULL) + { + *err = result; + } + + return devInfo; + } + + for(cl::Device d : devs) + { + typename detail::param_traits< + detail::cl_program_build_info, name>::param_type param; + result = getBuildInfo(d, name, ¶m); + devInfo.push_back( + std::pair::param_type> + (d, param)); + if(result != CL_SUCCESS) + { + //On error, leave the loop and return the error code + break; + } + } + if(err != NULL) + { + *err = result; + } + if(result != CL_SUCCESS) + { + devInfo.clear(); + } + + return devInfo; + } + + cl_int createKernels(vector* kernels) + { + cl_uint numKernels; + cl_int err = ::clCreateKernelsInProgram(object_, 0, NULL, &numKernels); + if(err != CL_SUCCESS) + { + return detail::errHandler(err, __CREATE_KERNELS_IN_PROGRAM_ERR); + } + + vector value(numKernels); + + err = ::clCreateKernelsInProgram( + object_, numKernels, value.data(), NULL); + if(err != CL_SUCCESS) + { + return detail::errHandler(err, __CREATE_KERNELS_IN_PROGRAM_ERR); + } + + if(kernels) + { + kernels->resize(value.size()); + + //Assign to param, constructing with retain behaviour + //to correctly capture each underlying CL object + for(size_type i = 0; i < value.size(); i++) + { + //We do not need to retain because this kernel is being created + //by the runtime + (*kernels)[i] = Kernel(value[i], false); + } + } + + return CL_SUCCESS; + } +}; + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 +inline Program linkProgram( + Program input1, + Program input2, + const char* options = NULL, + void(CL_CALLBACK* notifyFptr)(cl_program, void*) = NULL, + void* data = NULL, + cl_int* err = NULL) +{ + cl_int error_local = CL_SUCCESS; + + cl_program programs[2] = { input1(), input2() }; + + Context ctx = input1.getInfo(&error_local); + if(error_local != CL_SUCCESS) + { + detail::errHandler(error_local, __LINK_PROGRAM_ERR); + } + + cl_program prog = ::clLinkProgram( + ctx(), + 0, + NULL, + options, + 2, + programs, + notifyFptr, + data, + &error_local); + + detail::errHandler(error_local, __COMPILE_PROGRAM_ERR); + if(err != NULL) + { + *err = error_local; + } + + return Program(prog); +} + +inline Program linkProgram( + vector inputPrograms, + const char* options = NULL, + void(CL_CALLBACK* notifyFptr)(cl_program, void*) = NULL, + void* data = NULL, + cl_int* err = NULL) +{ + cl_int error_local = CL_SUCCESS; + + vector programs(inputPrograms.size()); + + for(unsigned int i = 0; i < inputPrograms.size(); i++) + { + programs[i] = inputPrograms[i](); + } + + Context ctx; + if(inputPrograms.size() > 0) + { + ctx = inputPrograms[0].getInfo(&error_local); + if(error_local != CL_SUCCESS) + { + detail::errHandler(error_local, __LINK_PROGRAM_ERR); + } + } + cl_program prog = ::clLinkProgram( + ctx(), + 0, + NULL, + options, + (cl_uint)inputPrograms.size(), + programs.data(), + notifyFptr, + data, + &error_local); + + detail::errHandler(error_local, __COMPILE_PROGRAM_ERR); + if(err != NULL) + { + *err = error_local; + } + + return Program(prog, false); +} + +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 + +//Template specialization for CL_PROGRAM_BINARIES +template<> +inline cl_int cl::Program::getInfo(cl_program_info name, + vector >* param) const +{ + if(name != CL_PROGRAM_BINARIES) + { + return CL_INVALID_VALUE; + } + if(param) + { + //Resize the parameter array appropriately for each allocation + //and pass down to the helper + + vector sizes = getInfo(); + size_type numBinaries = sizes.size(); + + //Resize the parameter array and constituent arrays + param->resize(numBinaries); + for(size_type i = 0; i < numBinaries; ++i) + { + (*param)[i].resize(sizes[i]); + } + + return detail::errHandler( + detail::getInfo(&::clGetProgramInfo, object_, name, param), + __GET_PROGRAM_INFO_ERR); + } + + return CL_SUCCESS; +} + +template<> +inline vector > cl::Program::getInfo(cl_int* err) const +{ + vector > binariesVectors; + + cl_int result = getInfo(CL_PROGRAM_BINARIES, &binariesVectors); + if(err != NULL) + { + *err = result; + } + + return binariesVectors; +} + +inline Kernel::Kernel(const Program& program, const char* name, cl_int* err) +{ + cl_int error; + + object_ = ::clCreateKernel(program(), name, &error); + detail::errHandler(error, __CREATE_KERNEL_ERR); + + if(err != NULL) + { + *err = error; + } +} + +enum class QueueProperties : cl_command_queue_properties +{ + None = 0, + Profiling = CL_QUEUE_PROFILING_ENABLE, + OutOfOrder = CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, +}; + +inline QueueProperties operator|(QueueProperties lhs, + QueueProperties rhs) +{ + return static_cast(static_cast(lhs) | + static_cast(rhs)); +} + +/*! \class CommandQueue + * \brief CommandQueue interface for cl_command_queue. + */ +class CommandQueue : public detail::Wrapper +{ +private: + static std::once_flag default_initialized_; + static CommandQueue default_; + static cl_int default_error_; + + /*! \brief Create the default command queue returned by @ref getDefault. + * + * It sets default_error_ to indicate success or failure. It does not throw + * @c cl::Error. + */ + static void makeDefault() + { + /* We don't want to throw an error from this function, so we have to + * catch and set the error flag. + */ +#if defined(CL_HPP_ENABLE_EXCEPTIONS) + try +#endif + { + int error; + Context context = Context::getDefault(&error); + + if(error != CL_SUCCESS) + { + default_error_ = error; + } + else + { + Device device = Device::getDefault(); + default_ = CommandQueue(context, device, 0, &default_error_); + } + } +#if defined(CL_HPP_ENABLE_EXCEPTIONS) + catch(cl::Error& e) + { + default_error_ = e.err(); + } +#endif + } + + /*! \brief Create the default command queue. + * + * This sets @c default_. It does not throw + * @c cl::Error. + */ + static void makeDefaultProvided(const CommandQueue& c) { + default_ = c; + } + +public: +#ifdef CL_HPP_UNIT_TEST_ENABLE + /*! \brief Reset the default. + * + * This sets @c default_ to an empty value to support cleanup in + * the unit test framework. + * This function is not thread safe. + */ + static void unitTestClearDefault() { + default_ = CommandQueue(); + } + +#endif //#ifdef CL_HPP_UNIT_TEST_ENABLE + + /*! + * \brief Constructs a CommandQueue based on passed properties. + * Will return an CL_INVALID_QUEUE_PROPERTIES error if CL_QUEUE_ON_DEVICE is specified. + */ + CommandQueue( + cl_command_queue_properties properties, + cl_int* err = NULL) + { + cl_int error; + + Context context = Context::getDefault(&error); + detail::errHandler(error, __CREATE_CONTEXT_ERR); + + if(error != CL_SUCCESS) + { + if(err != NULL) + { + *err = error; + } + } + else + { + Device device = context.getInfo()[0]; + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + cl_queue_properties queue_properties[] = { + CL_QUEUE_PROPERTIES, properties, 0 }; + if((properties & CL_QUEUE_ON_DEVICE) == 0) + { + object_ = ::clCreateCommandQueueWithProperties( + context(), device(), queue_properties, &error); + } + else + { + error = CL_INVALID_QUEUE_PROPERTIES; + } + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_WITH_PROPERTIES_ERR); + if(err != NULL) + { + *err = error; + } +#else + object_ = ::clCreateCommandQueue( + context(), device(), properties, &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_ERR); + if(err != NULL) + { + *err = error; + } +#endif + } + } + + /*! + * \brief Constructs a CommandQueue based on passed properties. + * Will return an CL_INVALID_QUEUE_PROPERTIES error if CL_QUEUE_ON_DEVICE is specified. + */ + CommandQueue( + QueueProperties properties, + cl_int* err = NULL) + { + cl_int error; + + Context context = Context::getDefault(&error); + detail::errHandler(error, __CREATE_CONTEXT_ERR); + + if(error != CL_SUCCESS) + { + if(err != NULL) + { + *err = error; + } + } + else + { + Device device = context.getInfo()[0]; + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + cl_queue_properties queue_properties[] = { + CL_QUEUE_PROPERTIES, static_cast(properties), 0 }; + + object_ = ::clCreateCommandQueueWithProperties( + context(), device(), queue_properties, &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_WITH_PROPERTIES_ERR); + if(err != NULL) + { + *err = error; + } +#else + object_ = ::clCreateCommandQueue( + context(), device(), static_cast(properties), &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_ERR); + if(err != NULL) + { + *err = error; + } +#endif + } + } + + /*! + * \brief Constructs a CommandQueue for an implementation defined device in the given context + * Will return an CL_INVALID_QUEUE_PROPERTIES error if CL_QUEUE_ON_DEVICE is specified. + */ + explicit CommandQueue( + const Context& context, + cl_command_queue_properties properties = 0, + cl_int* err = NULL) + { + cl_int error; + vector devices; + error = context.getInfo(CL_CONTEXT_DEVICES, &devices); + + detail::errHandler(error, __CREATE_CONTEXT_ERR); + + if(error != CL_SUCCESS) + { + if(err != NULL) + { + *err = error; + } + + return; + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + cl_queue_properties queue_properties[] = { + CL_QUEUE_PROPERTIES, properties, 0 }; + if((properties & CL_QUEUE_ON_DEVICE) == 0) + { + object_ = ::clCreateCommandQueueWithProperties( + context(), devices[0](), queue_properties, &error); + } + else + { + error = CL_INVALID_QUEUE_PROPERTIES; + } + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_WITH_PROPERTIES_ERR); + if(err != NULL) + { + *err = error; + } +#else + object_ = ::clCreateCommandQueue( + context(), devices[0](), properties, &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_ERR); + if(err != NULL) + { + *err = error; + } +#endif + } + + /*! + * \brief Constructs a CommandQueue for an implementation defined device in the given context + * Will return an CL_INVALID_QUEUE_PROPERTIES error if CL_QUEUE_ON_DEVICE is specified. + */ + explicit CommandQueue( + const Context& context, + QueueProperties properties, + cl_int* err = NULL) + { + cl_int error; + vector devices; + error = context.getInfo(CL_CONTEXT_DEVICES, &devices); + + detail::errHandler(error, __CREATE_CONTEXT_ERR); + + if(error != CL_SUCCESS) + { + if(err != NULL) + { + *err = error; + } + + return; + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + cl_queue_properties queue_properties[] = { + CL_QUEUE_PROPERTIES, static_cast(properties), 0 }; + object_ = ::clCreateCommandQueueWithProperties( + context(), devices[0](), queue_properties, &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_WITH_PROPERTIES_ERR); + if(err != NULL) + { + *err = error; + } +#else + object_ = ::clCreateCommandQueue( + context(), devices[0](), static_cast(properties), &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_ERR); + if(err != NULL) + { + *err = error; + } +#endif + } + + /*! + * \brief Constructs a CommandQueue for a passed device and context + * Will return an CL_INVALID_QUEUE_PROPERTIES error if CL_QUEUE_ON_DEVICE is specified. + */ + CommandQueue( + const Context& context, + const Device& device, + cl_command_queue_properties properties = 0, + cl_int* err = NULL) + { + cl_int error; + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + cl_queue_properties queue_properties[] = { + CL_QUEUE_PROPERTIES, properties, 0 }; + object_ = ::clCreateCommandQueueWithProperties( + context(), device(), queue_properties, &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_WITH_PROPERTIES_ERR); + if(err != NULL) + { + *err = error; + } +#else + object_ = ::clCreateCommandQueue( + context(), device(), properties, &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_ERR); + if(err != NULL) + { + *err = error; + } +#endif + } + + /*! + * \brief Constructs a CommandQueue for a passed device and context + * Will return an CL_INVALID_QUEUE_PROPERTIES error if CL_QUEUE_ON_DEVICE is specified. + */ + CommandQueue( + const Context& context, + const Device& device, + QueueProperties properties, + cl_int* err = NULL) + { + cl_int error; + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + cl_queue_properties queue_properties[] = { + CL_QUEUE_PROPERTIES, static_cast(properties), 0 }; + object_ = ::clCreateCommandQueueWithProperties( + context(), device(), queue_properties, &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_WITH_PROPERTIES_ERR); + if(err != NULL) + { + *err = error; + } +#else + object_ = ::clCreateCommandQueue( + context(), device(), static_cast(properties), &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_ERR); + if(err != NULL) + { + *err = error; + } +#endif + } + + static CommandQueue getDefault(cl_int* err = NULL) + { + std::call_once(default_initialized_, makeDefault); +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + detail::errHandler(default_error_, __CREATE_COMMAND_QUEUE_WITH_PROPERTIES_ERR); +#else //CL_HPP_TARGET_OPENCL_VERSION >= 200 + detail::errHandler(default_error_, __CREATE_COMMAND_QUEUE_ERR); +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 200 + if(err != NULL) + { + *err = default_error_; + } + + return default_; + } + + /** + * Modify the default command queue to be used by + * subsequent operations. + * Will only set the default if no default was previously created. + * @return updated default command queue. + * Should be compared to the passed value to ensure that it was updated. + */ + static CommandQueue setDefault(const CommandQueue& default_queue) + { + std::call_once(default_initialized_, makeDefaultProvided, std::cref(default_queue)); + detail::errHandler(default_error_); + + return default_; + } + + CommandQueue() + { + } + + /*! \brief Constructor from cl_mem - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + */ + explicit CommandQueue(const cl_command_queue& commandQueue, bool retainObject = false) : + detail::Wrapper(commandQueue, retainObject) + { + } + + CommandQueue& operator= (const cl_command_queue& rhs) + { + detail::Wrapper::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + CommandQueue(const CommandQueue& queue) : detail::Wrapper(queue) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + CommandQueue& operator= (const CommandQueue& queue) + { + detail::Wrapper::operator=(queue); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + CommandQueue(CommandQueue&& queue) CL_HPP_NOEXCEPT_ : detail::Wrapper(std::move(queue)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + CommandQueue& operator= (CommandQueue&& queue) + { + detail::Wrapper::operator=(std::move(queue)); + + return *this; + } + + template + cl_int getInfo(cl_command_queue_info name, T* param) const + { + return detail::errHandler( + detail::getInfo( + &::clGetCommandQueueInfo, object_, name, param), + __GET_COMMAND_QUEUE_INFO_ERR); + } + + template typename + detail::param_traits::param_type getInfo( + cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_command_queue_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } + + cl_int enqueueReadBuffer( + const Buffer& buffer, + cl_bool blocking, + size_type offset, + size_type size, + void* ptr, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueReadBuffer( + object_, buffer(), blocking, offset, size, + ptr, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_READ_BUFFER_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + cl_int enqueueWriteBuffer( + const Buffer& buffer, + cl_bool blocking, + size_type offset, + size_type size, + const void* ptr, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueWriteBuffer( + object_, buffer(), blocking, offset, size, + ptr, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_WRITE_BUFFER_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + cl_int enqueueCopyBuffer( + const Buffer& src, + const Buffer& dst, + size_type src_offset, + size_type dst_offset, + size_type size, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueCopyBuffer( + object_, src(), dst(), src_offset, dst_offset, size, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQEUE_COPY_BUFFER_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + cl_int enqueueReadBufferRect( + const Buffer& buffer, + cl_bool blocking, + const array& buffer_offset, + const array& host_offset, + const array& region, + size_type buffer_row_pitch, + size_type buffer_slice_pitch, + size_type host_row_pitch, + size_type host_slice_pitch, + void* ptr, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueReadBufferRect( + object_, + buffer(), + blocking, + buffer_offset.data(), + host_offset.data(), + region.data(), + buffer_row_pitch, + buffer_slice_pitch, + host_row_pitch, + host_slice_pitch, + ptr, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_READ_BUFFER_RECT_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + cl_int enqueueWriteBufferRect( + const Buffer& buffer, + cl_bool blocking, + const array& buffer_offset, + const array& host_offset, + const array& region, + size_type buffer_row_pitch, + size_type buffer_slice_pitch, + size_type host_row_pitch, + size_type host_slice_pitch, + const void* ptr, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueWriteBufferRect( + object_, + buffer(), + blocking, + buffer_offset.data(), + host_offset.data(), + region.data(), + buffer_row_pitch, + buffer_slice_pitch, + host_row_pitch, + host_slice_pitch, + ptr, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_WRITE_BUFFER_RECT_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + cl_int enqueueCopyBufferRect( + const Buffer& src, + const Buffer& dst, + const array& src_origin, + const array& dst_origin, + const array& region, + size_type src_row_pitch, + size_type src_slice_pitch, + size_type dst_row_pitch, + size_type dst_slice_pitch, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueCopyBufferRect( + object_, + src(), + dst(), + src_origin.data(), + dst_origin.data(), + region.data(), + src_row_pitch, + src_slice_pitch, + dst_row_pitch, + dst_slice_pitch, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQEUE_COPY_BUFFER_RECT_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + /** + * Enqueue a command to fill a buffer object with a pattern + * of a given size. The pattern is specified as a vector type. + * \tparam PatternType The datatype of the pattern field. + * The pattern type must be an accepted OpenCL data type. + * \tparam offset Is the offset in bytes into the buffer at + * which to start filling. This must be a multiple of + * the pattern size. + * \tparam size Is the size in bytes of the region to fill. + * This must be a multiple of the pattern size. + */ + template + cl_int enqueueFillBuffer( + const Buffer& buffer, + PatternType pattern, + size_type offset, + size_type size, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueFillBuffer( + object_, + buffer(), + static_cast(&pattern), + sizeof(PatternType), + offset, + size, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_FILL_BUFFER_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 + + cl_int enqueueReadImage( + const Image& image, + cl_bool blocking, + const array& origin, + const array& region, + size_type row_pitch, + size_type slice_pitch, + void* ptr, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueReadImage( + object_, + image(), + blocking, + origin.data(), + region.data(), + row_pitch, + slice_pitch, + ptr, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_READ_IMAGE_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + cl_int enqueueWriteImage( + const Image& image, + cl_bool blocking, + const array& origin, + const array& region, + size_type row_pitch, + size_type slice_pitch, + const void* ptr, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueWriteImage( + object_, + image(), + blocking, + origin.data(), + region.data(), + row_pitch, + slice_pitch, + ptr, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_WRITE_IMAGE_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + cl_int enqueueCopyImage( + const Image& src, + const Image& dst, + const array& src_origin, + const array& dst_origin, + const array& region, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueCopyImage( + object_, + src(), + dst(), + src_origin.data(), + dst_origin.data(), + region.data(), + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_COPY_IMAGE_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + /** + * Enqueue a command to fill an image object with a specified color. + * \param fillColor is the color to use to fill the image. + * This is a four component RGBA floating-point color value if + * the image channel data type is not an unnormalized signed or + * unsigned data type. + */ + cl_int enqueueFillImage( + const Image& image, + cl_float4 fillColor, + const array& origin, + const array& region, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueFillImage( + object_, + image(), + static_cast(&fillColor), + origin.data(), + region.data(), + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_FILL_IMAGE_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + /** + * Enqueue a command to fill an image object with a specified color. + * \param fillColor is the color to use to fill the image. + * This is a four component RGBA signed integer color value if + * the image channel data type is an unnormalized signed integer + * type. + */ + cl_int enqueueFillImage( + const Image& image, + cl_int4 fillColor, + const array& origin, + const array& region, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueFillImage( + object_, + image(), + static_cast(&fillColor), + origin.data(), + region.data(), + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_FILL_IMAGE_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + /** + * Enqueue a command to fill an image object with a specified color. + * \param fillColor is the color to use to fill the image. + * This is a four component RGBA unsigned integer color value if + * the image channel data type is an unnormalized unsigned integer + * type. + */ + cl_int enqueueFillImage( + const Image& image, + cl_uint4 fillColor, + const array& origin, + const array& region, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueFillImage( + object_, + image(), + static_cast(&fillColor), + origin.data(), + region.data(), + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_FILL_IMAGE_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 + + cl_int enqueueCopyImageToBuffer( + const Image& src, + const Buffer& dst, + const array& src_origin, + const array& region, + size_type dst_offset, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueCopyImageToBuffer( + object_, + src(), + dst(), + src_origin.data(), + region.data(), + dst_offset, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_COPY_IMAGE_TO_BUFFER_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + cl_int enqueueCopyBufferToImage( + const Buffer& src, + const Image& dst, + size_type src_offset, + const array& dst_origin, + const array& region, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueCopyBufferToImage( + object_, + src(), + dst(), + src_offset, + dst_origin.data(), + region.data(), + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_COPY_BUFFER_TO_IMAGE_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + void* enqueueMapBuffer( + const Buffer& buffer, + cl_bool blocking, + cl_map_flags flags, + size_type offset, + size_type size, + const vector* events = NULL, + Event* event = NULL, + cl_int* err = NULL) const + { + cl_event tmp; + cl_int error; + void* result = ::clEnqueueMapBuffer( + object_, buffer(), blocking, flags, offset, size, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL, + &error); + + detail::errHandler(error, __ENQUEUE_MAP_BUFFER_ERR); + if(err != NULL) + { + *err = error; + } + if(event != NULL && error == CL_SUCCESS) + { + *event = tmp; + } + + return result; + } + + void* enqueueMapImage( + const Image& buffer, + cl_bool blocking, + cl_map_flags flags, + const array& origin, + const array& region, + size_type* row_pitch, + size_type* slice_pitch, + const vector* events = NULL, + Event* event = NULL, + cl_int* err = NULL) const + { + cl_event tmp; + cl_int error; + void* result = ::clEnqueueMapImage( + object_, buffer(), blocking, flags, + origin.data(), + region.data(), + row_pitch, slice_pitch, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL, + &error); + + detail::errHandler(error, __ENQUEUE_MAP_IMAGE_ERR); + if(err != NULL) + { + *err = error; + } + if(event != NULL && error == CL_SUCCESS) + { + *event = tmp; + } + + return result; + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + /** + * Enqueues a command that will allow the host to update a region of a coarse-grained SVM + *buffer. + * This variant takes a raw SVM pointer. + */ + template + cl_int enqueueMapSVM( + T* ptr, + cl_bool blocking, + cl_map_flags flags, + size_type size, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler(::clEnqueueSVMMap( + object_, blocking, flags, static_cast(ptr), size, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && + events->size() > + 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_MAP_BUFFER_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + /** + * Enqueues a command that will allow the host to update a region of a coarse-grained SVM + *buffer. + * This variant takes a cl::pointer instance. + */ + template + cl_int enqueueMapSVM( + cl::pointer& ptr, + cl_bool blocking, + cl_map_flags flags, + size_type size, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler(::clEnqueueSVMMap( + object_, blocking, flags, static_cast(ptr.get()), + size, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && + events->size() > + 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_MAP_BUFFER_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + /** + * Enqueues a command that will allow the host to update a region of a coarse-grained SVM + *buffer. + * This variant takes a cl::vector instance. + */ + template + cl_int enqueueMapSVM( + cl::vector& container, + cl_bool blocking, + cl_map_flags flags, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler(::clEnqueueSVMMap( + object_, blocking, flags, + static_cast(container.data()), container.size(), + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && + events->size() > + 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_MAP_BUFFER_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + + cl_int enqueueUnmapMemObject( + const Memory& memory, + void* mapped_ptr, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueUnmapMemObject( + object_, memory(), mapped_ptr, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_UNMAP_MEM_OBJECT_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + /** + * Enqueues a command that will release a coarse-grained SVM buffer back to the OpenCL runtime. + * This variant takes a raw SVM pointer. + */ + template + cl_int enqueueUnmapSVM( + T* ptr, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueSVMUnmap( + object_, static_cast(ptr), + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_UNMAP_MEM_OBJECT_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + /** + * Enqueues a command that will release a coarse-grained SVM buffer back to the OpenCL runtime. + * This variant takes a cl::pointer instance. + */ + template + cl_int enqueueUnmapSVM( + cl::pointer& ptr, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueSVMUnmap( + object_, static_cast(ptr.get()), + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_UNMAP_MEM_OBJECT_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + /** + * Enqueues a command that will release a coarse-grained SVM buffer back to the OpenCL runtime. + * This variant takes a cl::vector instance. + */ + template + cl_int enqueueUnmapSVM( + cl::vector& container, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueSVMUnmap( + object_, static_cast(container.data()), + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_UNMAP_MEM_OBJECT_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + /** + * Enqueues a marker command which waits for either a list of events to complete, + * or all previously enqueued commands to complete. + * + * Enqueues a marker command which waits for either a list of events to complete, + * or if the list is empty it waits for all commands previously enqueued in command_queue + * to complete before it completes. This command returns an event which can be waited on, + * i.e. this event can be waited on to insure that all events either in the event_wait_list + * or all previously enqueued commands, queued before this command to command_queue, + * have completed. + */ + cl_int enqueueMarkerWithWaitList( + const vector* events = 0, + Event* event = 0) + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueMarkerWithWaitList( + object_, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_MARKER_WAIT_LIST_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + /** + * A synchronization point that enqueues a barrier operation. + * + * Enqueues a barrier command which waits for either a list of events to complete, + * or if the list is empty it waits for all commands previously enqueued in command_queue + * to complete before it completes. This command blocks command execution, that is, any + * following commands enqueued after it do not execute until it completes. This command + * returns an event which can be waited on, i.e. this event can be waited on to insure that + * all events either in the event_wait_list or all previously enqueued commands, queued + * before this command to command_queue, have completed. + */ + cl_int enqueueBarrierWithWaitList( + const vector* events = 0, + Event* event = 0) + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueBarrierWithWaitList( + object_, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_BARRIER_WAIT_LIST_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + /** + * Enqueues a command to indicate with which device a set of memory objects + * should be associated. + */ + cl_int enqueueMigrateMemObjects( + const vector& memObjects, + cl_mem_migration_flags flags, + const vector* events = NULL, + Event* event = NULL + ) + { + cl_event tmp; + + vector localMemObjects(memObjects.size()); + + for(int i = 0; i < (int)memObjects.size(); ++i) + { + localMemObjects[i] = memObjects[i](); + } + + cl_int err = detail::errHandler( + ::clEnqueueMigrateMemObjects( + object_, + (cl_uint)memObjects.size(), + localMemObjects.data(), + flags, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_UNMAP_MEM_OBJECT_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 + + cl_int enqueueNDRangeKernel( + const Kernel& kernel, + const NDRange& offset, + const NDRange& global, + const NDRange& local = NullRange, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueNDRangeKernel( + object_, kernel(), (cl_uint)global.dimensions(), + offset.dimensions() != 0 ? (const size_type*)offset : NULL, + (const size_type*)global, + local.dimensions() != 0 ? (const size_type*)local : NULL, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_NDRANGE_KERNEL_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + +#if defined(CL_USE_DEPRECATED_OPENCL_1_2_APIS) + CL_EXT_PREFIX__VERSION_1_2_DEPRECATED cl_int enqueueTask( + const Kernel& kernel, + const vector* events = NULL, + Event* event = NULL) const CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueTask( + object_, kernel(), + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_TASK_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + +#endif //#if defined(CL_USE_DEPRECATED_OPENCL_1_2_APIS) + + cl_int enqueueNativeKernel( + void(CL_CALLBACK* userFptr)(void*), + std::pair args, + const vector* mem_objects = NULL, + const vector* mem_locs = NULL, + const vector* events = NULL, + Event* event = NULL) const + { + size_type elements = 0; + if(mem_objects != NULL) + { + elements = mem_objects->size(); + } + vector mems(elements); + for(unsigned int i = 0; i < elements; i++) + { + mems[i] = ((*mem_objects)[i])(); + } + + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueNativeKernel( + object_, userFptr, args.first, args.second, + (mem_objects != NULL) ? (cl_uint)mem_objects->size() : 0, + mems.data(), + (mem_locs != NULL && + mem_locs->size() > 0) ? (const void**)&mem_locs->front() : NULL, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_NATIVE_KERNEL); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + +/** + * Deprecated APIs for 1.2 + */ +#if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + CL_EXT_PREFIX__VERSION_1_1_DEPRECATED + cl_int enqueueMarker(Event* event = NULL) const CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueMarker( + object_, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_MARKER_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + CL_EXT_PREFIX__VERSION_1_1_DEPRECATED + cl_int enqueueWaitForEvents(const vector& events) const + CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED + { + return detail::errHandler( + ::clEnqueueWaitForEvents( + object_, + (cl_uint)events.size(), + events.size() > 0 ? (const cl_event*)&events.front() : NULL), + __ENQUEUE_WAIT_FOR_EVENTS_ERR); + } + +#endif //defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + + cl_int enqueueAcquireGLObjects( + const vector* mem_objects = NULL, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueAcquireGLObjects( + object_, + (mem_objects != NULL) ? (cl_uint)mem_objects->size() : 0, + (mem_objects != NULL && + mem_objects->size() > 0) ? (const cl_mem*)&mem_objects->front() : NULL, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_ACQUIRE_GL_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + cl_int enqueueReleaseGLObjects( + const vector* mem_objects = NULL, + const vector* events = NULL, + Event* event = NULL) const + { + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueReleaseGLObjects( + object_, + (mem_objects != NULL) ? (cl_uint)mem_objects->size() : 0, + (mem_objects != NULL && + mem_objects->size() > 0) ? (const cl_mem*)&mem_objects->front() : NULL, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_RELEASE_GL_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + +#if defined (CL_HPP_USE_DX_INTEROP) + typedef CL_API_ENTRY cl_int (CL_API_CALL* PFN_clEnqueueAcquireD3D10ObjectsKHR)( + cl_command_queue command_queue, cl_uint num_objects, + const cl_mem* mem_objects, cl_uint num_events_in_wait_list, + const cl_event* event_wait_list, cl_event* event); + typedef CL_API_ENTRY cl_int (CL_API_CALL* PFN_clEnqueueReleaseD3D10ObjectsKHR)( + cl_command_queue command_queue, cl_uint num_objects, + const cl_mem* mem_objects, cl_uint num_events_in_wait_list, + const cl_event* event_wait_list, cl_event* event); + + cl_int enqueueAcquireD3D10Objects( + const vector* mem_objects = NULL, + const vector* events = NULL, + Event* event = NULL) const + { + static PFN_clEnqueueAcquireD3D10ObjectsKHR pfn_clEnqueueAcquireD3D10ObjectsKHR = NULL; +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + cl_context context = getInfo(); + cl::Device device(getInfo()); + cl_platform_id platform = device.getInfo(); + CL_HPP_INIT_CL_EXT_FCN_PTR_PLATFORM_(platform, clEnqueueAcquireD3D10ObjectsKHR); +#endif +#if CL_HPP_TARGET_OPENCL_VERSION >= 110 + CL_HPP_INIT_CL_EXT_FCN_PTR_(clEnqueueAcquireD3D10ObjectsKHR); +#endif + + cl_event tmp; + cl_int err = detail::errHandler( + pfn_clEnqueueAcquireD3D10ObjectsKHR( + object_, + (mem_objects != NULL) ? (cl_uint)mem_objects->size() : 0, + (mem_objects != NULL && + mem_objects->size() > 0) ? (const cl_mem*)&mem_objects->front() : NULL, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_ACQUIRE_GL_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + + cl_int enqueueReleaseD3D10Objects( + const vector* mem_objects = NULL, + const vector* events = NULL, + Event* event = NULL) const + { + static PFN_clEnqueueReleaseD3D10ObjectsKHR pfn_clEnqueueReleaseD3D10ObjectsKHR = NULL; +#if CL_HPP_TARGET_OPENCL_VERSION >= 120 + cl_context context = getInfo(); + cl::Device device(getInfo()); + cl_platform_id platform = device.getInfo(); + CL_HPP_INIT_CL_EXT_FCN_PTR_PLATFORM_(platform, clEnqueueReleaseD3D10ObjectsKHR); +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 120 +#if CL_HPP_TARGET_OPENCL_VERSION >= 110 + CL_HPP_INIT_CL_EXT_FCN_PTR_(clEnqueueReleaseD3D10ObjectsKHR); +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 110 + + cl_event tmp; + cl_int err = detail::errHandler( + pfn_clEnqueueReleaseD3D10ObjectsKHR( + object_, + (mem_objects != NULL) ? (cl_uint)mem_objects->size() : 0, + (mem_objects != NULL && + mem_objects->size() > 0) ? (const cl_mem*)&mem_objects->front() : NULL, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_RELEASE_GL_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; + } + +#endif + +/** + * Deprecated APIs for 1.2 + */ +#if defined(CL_USE_DEPRECATED_OPENCL_1_1_APIS) + CL_EXT_PREFIX__VERSION_1_1_DEPRECATED + cl_int enqueueBarrier() const CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED + { + return detail::errHandler( + ::clEnqueueBarrier(object_), + __ENQUEUE_BARRIER_ERR); + } + +#endif //CL_USE_DEPRECATED_OPENCL_1_1_APIS + + cl_int flush() const + { + return detail::errHandler(::clFlush(object_), __FLUSH_ERR); + } + + cl_int finish() const + { + return detail::errHandler(::clFinish(object_), __FINISH_ERR); + } +}; //CommandQueue + +CL_HPP_DEFINE_STATIC_MEMBER_ std::once_flag CommandQueue::default_initialized_; +CL_HPP_DEFINE_STATIC_MEMBER_ CommandQueue CommandQueue::default_; +CL_HPP_DEFINE_STATIC_MEMBER_ cl_int CommandQueue::default_error_ = CL_SUCCESS; + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 +enum class DeviceQueueProperties : cl_command_queue_properties +{ + None = 0, + Profiling = CL_QUEUE_PROFILING_ENABLE, +}; + +inline DeviceQueueProperties operator|(DeviceQueueProperties lhs, + DeviceQueueProperties rhs) +{ + return static_cast(static_cast(lhs) | + static_cast(rhs)); +} + +/*! \class DeviceCommandQueue + * \brief DeviceCommandQueue interface for device cl_command_queues. + */ +class DeviceCommandQueue : public detail::Wrapper +{ +public: + /*! + * Trivial empty constructor to create a null queue. + */ + DeviceCommandQueue() + { + } + + /*! + * Default construct device command queue on default context and device + */ + DeviceCommandQueue(DeviceQueueProperties properties, cl_int* err = NULL) + { + cl_int error; + cl::Context context = cl::Context::getDefault(); + cl::Device device = cl::Device::getDefault(); + + cl_command_queue_properties mergedProperties = + CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE | CL_QUEUE_ON_DEVICE | + static_cast(properties); + + cl_queue_properties queue_properties[] = { + CL_QUEUE_PROPERTIES, mergedProperties, 0 }; + object_ = ::clCreateCommandQueueWithProperties( + context(), device(), queue_properties, &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_WITH_PROPERTIES_ERR); + if(err != NULL) + { + *err = error; + } + } + + /*! + * Create a device command queue for a specified device in the passed context. + */ + DeviceCommandQueue( + const Context& context, + const Device& device, + DeviceQueueProperties properties = DeviceQueueProperties::None, + cl_int* err = NULL) + { + cl_int error; + + cl_command_queue_properties mergedProperties = + CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE | CL_QUEUE_ON_DEVICE | + static_cast(properties); + cl_queue_properties queue_properties[] = { + CL_QUEUE_PROPERTIES, mergedProperties, 0 }; + object_ = ::clCreateCommandQueueWithProperties( + context(), device(), queue_properties, &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_WITH_PROPERTIES_ERR); + if(err != NULL) + { + *err = error; + } + } + + /*! + * Create a device command queue for a specified device in the passed context. + */ + DeviceCommandQueue( + const Context& context, + const Device& device, + cl_uint queueSize, + DeviceQueueProperties properties = DeviceQueueProperties::None, + cl_int* err = NULL) + { + cl_int error; + + cl_command_queue_properties mergedProperties = + CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE | CL_QUEUE_ON_DEVICE | + static_cast(properties); + cl_queue_properties queue_properties[] = { + CL_QUEUE_PROPERTIES, mergedProperties, + CL_QUEUE_SIZE, queueSize, + 0 }; + object_ = ::clCreateCommandQueueWithProperties( + context(), device(), queue_properties, &error); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_WITH_PROPERTIES_ERR); + if(err != NULL) + { + *err = error; + } + } + + /*! \brief Constructor from cl_command_queue - takes ownership. + * + * \param retainObject will cause the constructor to retain its cl object. + * Defaults to false to maintain compatibility with + * earlier versions. + */ + explicit DeviceCommandQueue(const cl_command_queue& commandQueue, bool retainObject = false) : + detail::Wrapper(commandQueue, retainObject) + { + } + + DeviceCommandQueue& operator= (const cl_command_queue& rhs) + { + detail::Wrapper::operator=(rhs); + + return *this; + } + + /*! \brief Copy constructor to forward copy to the superclass correctly. + * Required for MSVC. + */ + DeviceCommandQueue(const DeviceCommandQueue& queue) : detail::Wrapper(queue) + { + } + + /*! \brief Copy assignment to forward copy to the superclass correctly. + * Required for MSVC. + */ + DeviceCommandQueue& operator= (const DeviceCommandQueue& queue) + { + detail::Wrapper::operator=(queue); + + return *this; + } + + /*! \brief Move constructor to forward move to the superclass correctly. + * Required for MSVC. + */ + DeviceCommandQueue(DeviceCommandQueue&& queue) CL_HPP_NOEXCEPT_ : detail::Wrapper(std::move( + queue)) + { + } + + /*! \brief Move assignment to forward move to the superclass correctly. + * Required for MSVC. + */ + DeviceCommandQueue& operator= (DeviceCommandQueue&& queue) + { + detail::Wrapper::operator=(std::move(queue)); + + return *this; + } + + template + cl_int getInfo(cl_command_queue_info name, T* param) const + { + return detail::errHandler( + detail::getInfo( + &::clGetCommandQueueInfo, object_, name, param), + __GET_COMMAND_QUEUE_INFO_ERR); + } + + template typename + detail::param_traits::param_type getInfo( + cl_int* err = NULL) const + { + typename detail::param_traits< + detail::cl_command_queue_info, name>::param_type param; + cl_int result = getInfo(name, ¶m); + if(err != NULL) + { + *err = result; + } + + return param; + } + + /*! + * Create a new default device command queue for the default device, + * in the default context and of the default size. + * If there is already a default queue for the specified device this + * function will return the pre-existing queue. + */ + static DeviceCommandQueue makeDefault( + cl_int* err = nullptr) + { + cl_int error; + cl::Context context = cl::Context::getDefault(); + cl::Device device = cl::Device::getDefault(); + + cl_command_queue_properties properties = + CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE | CL_QUEUE_ON_DEVICE | + CL_QUEUE_ON_DEVICE_DEFAULT; + cl_queue_properties queue_properties[] = { + CL_QUEUE_PROPERTIES, properties, + 0 }; + DeviceCommandQueue deviceQueue( + ::clCreateCommandQueueWithProperties( + context(), device(), queue_properties, &error)); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_WITH_PROPERTIES_ERR); + if(err != NULL) + { + *err = error; + } + + return deviceQueue; + } + + /*! + * Create a new default device command queue for the specified device + * and of the default size. + * If there is already a default queue for the specified device this + * function will return the pre-existing queue. + */ + static DeviceCommandQueue makeDefault( + const Context& context, const Device& device, cl_int* err = nullptr) + { + cl_int error; + + cl_command_queue_properties properties = + CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE | CL_QUEUE_ON_DEVICE | + CL_QUEUE_ON_DEVICE_DEFAULT; + cl_queue_properties queue_properties[] = { + CL_QUEUE_PROPERTIES, properties, + 0 }; + DeviceCommandQueue deviceQueue( + ::clCreateCommandQueueWithProperties( + context(), device(), queue_properties, &error)); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_WITH_PROPERTIES_ERR); + if(err != NULL) + { + *err = error; + } + + return deviceQueue; + } + + /*! + * Create a new default device command queue for the specified device + * and of the requested size in bytes. + * If there is already a default queue for the specified device this + * function will return the pre-existing queue. + */ + static DeviceCommandQueue makeDefault( + const Context& context, const Device& device, cl_uint queueSize, cl_int* err = nullptr) + { + cl_int error; + + cl_command_queue_properties properties = + CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE | CL_QUEUE_ON_DEVICE | + CL_QUEUE_ON_DEVICE_DEFAULT; + cl_queue_properties queue_properties[] = { + CL_QUEUE_PROPERTIES, properties, + CL_QUEUE_SIZE, queueSize, + 0 }; + DeviceCommandQueue deviceQueue( + ::clCreateCommandQueueWithProperties( + context(), device(), queue_properties, &error)); + + detail::errHandler(error, __CREATE_COMMAND_QUEUE_WITH_PROPERTIES_ERR); + if(err != NULL) + { + *err = error; + } + + return deviceQueue; + } +}; //DeviceCommandQueue + +namespace detail +{ +//Specialization for device command queue +template<> +struct KernelArgumentHandler +{ + static size_type size(const cl::DeviceCommandQueue&) { + return sizeof(cl_command_queue); + } + + static const cl_command_queue* ptr(const cl::DeviceCommandQueue& value) { + return &(value()); + } +}; +} //namespace detail + +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + +template +Buffer::Buffer( + const Context& context, + IteratorType startIterator, + IteratorType endIterator, + bool readOnly, + bool useHostPtr, + cl_int* err) +{ + typedef typename std::iterator_traits::value_type DataType; + cl_int error; + + cl_mem_flags flags = 0; + if(readOnly) + { + flags |= CL_MEM_READ_ONLY; + } + else + { + flags |= CL_MEM_READ_WRITE; + } + if(useHostPtr) + { + flags |= CL_MEM_USE_HOST_PTR; + } + + size_type size = sizeof(DataType) * (endIterator - startIterator); + + if(useHostPtr) + { + object_ = ::clCreateBuffer(context(), + flags, + size, + static_cast(&*startIterator), + &error); + } + else + { + object_ = ::clCreateBuffer(context(), flags, size, 0, &error); + } + + detail::errHandler(error, __CREATE_BUFFER_ERR); + if(err != NULL) + { + *err = error; + } + + if(!useHostPtr) + { + CommandQueue queue(context, 0, &error); + detail::errHandler(error, __CREATE_BUFFER_ERR); + if(err != NULL) + { + *err = error; + } + + error = cl::copy(queue, startIterator, endIterator, *this); + detail::errHandler(error, __CREATE_BUFFER_ERR); + if(err != NULL) + { + *err = error; + } + } +} + +template +Buffer::Buffer( + const CommandQueue& queue, + IteratorType startIterator, + IteratorType endIterator, + bool readOnly, + bool useHostPtr, + cl_int* err) +{ + typedef typename std::iterator_traits::value_type DataType; + cl_int error; + + cl_mem_flags flags = 0; + if(readOnly) + { + flags |= CL_MEM_READ_ONLY; + } + else + { + flags |= CL_MEM_READ_WRITE; + } + if(useHostPtr) + { + flags |= CL_MEM_USE_HOST_PTR; + } + + size_type size = sizeof(DataType) * (endIterator - startIterator); + + Context context = queue.getInfo(); + + if(useHostPtr) + { + object_ = ::clCreateBuffer(context(), + flags, + size, + static_cast(&*startIterator), + &error); + } + else + { + object_ = ::clCreateBuffer(context(), flags, size, 0, &error); + } + + detail::errHandler(error, __CREATE_BUFFER_ERR); + if(err != NULL) + { + *err = error; + } + + if(!useHostPtr) + { + error = cl::copy(queue, startIterator, endIterator, *this); + detail::errHandler(error, __CREATE_BUFFER_ERR); + if(err != NULL) + { + *err = error; + } + } +} + +inline cl_int enqueueReadBuffer( + const Buffer& buffer, + cl_bool blocking, + size_type offset, + size_type size, + void* ptr, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if(error != CL_SUCCESS) + { + return error; + } + + return queue.enqueueReadBuffer(buffer, blocking, offset, size, ptr, events, event); +} + +inline cl_int enqueueWriteBuffer( + const Buffer& buffer, + cl_bool blocking, + size_type offset, + size_type size, + const void* ptr, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if(error != CL_SUCCESS) + { + return error; + } + + return queue.enqueueWriteBuffer(buffer, blocking, offset, size, ptr, events, event); +} + +inline void* enqueueMapBuffer( + const Buffer& buffer, + cl_bool blocking, + cl_map_flags flags, + size_type offset, + size_type size, + const vector* events = NULL, + Event* event = NULL, + cl_int* err = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + detail::errHandler(error, __ENQUEUE_MAP_BUFFER_ERR); + if(err != NULL) + { + *err = error; + } + + void* result = ::clEnqueueMapBuffer( + queue(), buffer(), blocking, flags, offset, size, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (cl_event*)event, + &error); + + detail::errHandler(error, __ENQUEUE_MAP_BUFFER_ERR); + if(err != NULL) + { + *err = error; + } + + return result; +} + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 +/** + * Enqueues to the default queue a command that will allow the host to + * update a region of a coarse-grained SVM buffer. + * This variant takes a raw SVM pointer. + */ +template +inline cl_int enqueueMapSVM( + T* ptr, + cl_bool blocking, + cl_map_flags flags, + size_type size, + const vector* events, + Event* event) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + if(error != CL_SUCCESS) + { + return detail::errHandler(error, __ENQUEUE_MAP_BUFFER_ERR); + } + + return queue.enqueueMapSVM( + ptr, blocking, flags, size, events, event); +} + +/** + * Enqueues to the default queue a command that will allow the host to + * update a region of a coarse-grained SVM buffer. + * This variant takes a cl::pointer instance. + */ +template +inline cl_int enqueueMapSVM( + cl::pointer ptr, + cl_bool blocking, + cl_map_flags flags, + size_type size, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + if(error != CL_SUCCESS) + { + return detail::errHandler(error, __ENQUEUE_MAP_BUFFER_ERR); + } + + return queue.enqueueMapSVM( + ptr, blocking, flags, size, events, event); +} + +/** + * Enqueues to the default queue a command that will allow the host to + * update a region of a coarse-grained SVM buffer. + * This variant takes a cl::vector instance. + */ +template +inline cl_int enqueueMapSVM( + cl::vector container, + cl_bool blocking, + cl_map_flags flags, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + if(error != CL_SUCCESS) + { + return detail::errHandler(error, __ENQUEUE_MAP_BUFFER_ERR); + } + + return queue.enqueueMapSVM( + container, blocking, flags, events, event); +} + +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + +inline cl_int enqueueUnmapMemObject( + const Memory& memory, + void* mapped_ptr, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + detail::errHandler(error, __ENQUEUE_MAP_BUFFER_ERR); + if(error != CL_SUCCESS) + { + return error; + } + + cl_event tmp; + cl_int err = detail::errHandler( + ::clEnqueueUnmapMemObject( + queue(), memory(), mapped_ptr, + (events != NULL) ? (cl_uint)events->size() : 0, + (events != NULL && events->size() > 0) ? (cl_event*)&events->front() : NULL, + (event != NULL) ? &tmp : NULL), + __ENQUEUE_UNMAP_MEM_OBJECT_ERR); + + if(event != NULL && err == CL_SUCCESS) + { + *event = tmp; + } + + return err; +} + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 +/** + * Enqueues to the default queue a command that will release a coarse-grained + * SVM buffer back to the OpenCL runtime. + * This variant takes a raw SVM pointer. + */ +template +inline cl_int enqueueUnmapSVM( + T* ptr, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + if(error != CL_SUCCESS) + { + return detail::errHandler(error, __ENQUEUE_UNMAP_MEM_OBJECT_ERR); + } + + return detail::errHandler(queue.enqueueUnmapSVM(ptr, events, event), + __ENQUEUE_UNMAP_MEM_OBJECT_ERR); +} + +/** + * Enqueues to the default queue a command that will release a coarse-grained + * SVM buffer back to the OpenCL runtime. + * This variant takes a cl::pointer instance. + */ +template +inline cl_int enqueueUnmapSVM( + cl::pointer& ptr, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + if(error != CL_SUCCESS) + { + return detail::errHandler(error, __ENQUEUE_UNMAP_MEM_OBJECT_ERR); + } + + return detail::errHandler(queue.enqueueUnmapSVM(ptr, events, event), + __ENQUEUE_UNMAP_MEM_OBJECT_ERR); +} + +/** + * Enqueues to the default queue a command that will release a coarse-grained + * SVM buffer back to the OpenCL runtime. + * This variant takes a cl::vector instance. + */ +template +inline cl_int enqueueUnmapSVM( + cl::vector& container, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + if(error != CL_SUCCESS) + { + return detail::errHandler(error, __ENQUEUE_UNMAP_MEM_OBJECT_ERR); + } + + return detail::errHandler(queue.enqueueUnmapSVM(container, events, event), + __ENQUEUE_UNMAP_MEM_OBJECT_ERR); +} + +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + +inline cl_int enqueueCopyBuffer( + const Buffer& src, + const Buffer& dst, + size_type src_offset, + size_type dst_offset, + size_type size, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if(error != CL_SUCCESS) + { + return error; + } + + return queue.enqueueCopyBuffer(src, dst, src_offset, dst_offset, size, events, event); +} + +/** + * Blocking copy operation between iterators and a buffer. + * Host to Device. + * Uses default command queue. + */ +template +inline cl_int copy(IteratorType startIterator, IteratorType endIterator, cl::Buffer& buffer) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + if(error != CL_SUCCESS) + { + return error; + } + + return cl::copy(queue, startIterator, endIterator, buffer); +} + +/** + * Blocking copy operation between iterators and a buffer. + * Device to Host. + * Uses default command queue. + */ +template +inline cl_int copy(const cl::Buffer& buffer, IteratorType startIterator, IteratorType endIterator) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + if(error != CL_SUCCESS) + { + return error; + } + + return cl::copy(queue, buffer, startIterator, endIterator); +} + +/** + * Blocking copy operation between iterators and a buffer. + * Host to Device. + * Uses specified queue. + */ +template +inline cl_int copy(const CommandQueue& queue, + IteratorType startIterator, + IteratorType endIterator, + cl::Buffer& buffer) +{ + typedef typename std::iterator_traits::value_type DataType; + cl_int error; + + size_type length = endIterator - startIterator; + size_type byteLength = length * sizeof(DataType); + + DataType* pointer = + static_cast(queue.enqueueMapBuffer(buffer, CL_TRUE, CL_MAP_WRITE, 0, byteLength, + 0, 0, &error)); + //if exceptions enabled, enqueueMapBuffer will throw + if(error != CL_SUCCESS) + { + return error; + } +#if defined(_MSC_VER) + std::copy( + startIterator, + endIterator, + stdext::checked_array_iterator( + pointer, length)); +#else + std::copy(startIterator, endIterator, pointer); +#endif + Event endEvent; + error = queue.enqueueUnmapMemObject(buffer, pointer, 0, &endEvent); + //if exceptions enabled, enqueueUnmapMemObject will throw + if(error != CL_SUCCESS) + { + return error; + } + endEvent.wait(); + + return CL_SUCCESS; +} + +/** + * Blocking copy operation between iterators and a buffer. + * Device to Host. + * Uses specified queue. + */ +template +inline cl_int copy(const CommandQueue& queue, + const cl::Buffer& buffer, + IteratorType startIterator, + IteratorType endIterator) +{ + typedef typename std::iterator_traits::value_type DataType; + cl_int error; + + size_type length = endIterator - startIterator; + size_type byteLength = length * sizeof(DataType); + + DataType* pointer = + static_cast(queue.enqueueMapBuffer(buffer, CL_TRUE, CL_MAP_READ, 0, byteLength, + 0, 0, &error)); + //if exceptions enabled, enqueueMapBuffer will throw + if(error != CL_SUCCESS) + { + return error; + } + std::copy(pointer, pointer + length, startIterator); + Event endEvent; + error = queue.enqueueUnmapMemObject(buffer, pointer, 0, &endEvent); + //if exceptions enabled, enqueueUnmapMemObject will throw + if(error != CL_SUCCESS) + { + return error; + } + endEvent.wait(); + + return CL_SUCCESS; +} + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 +/** + * Blocking SVM map operation - performs a blocking map underneath. + */ +template +inline cl_int mapSVM(cl::vector& container) +{ + return enqueueMapSVM(container, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE); +} + +/** + * Blocking SVM map operation - performs a blocking map underneath. + */ +template +inline cl_int unmapSVM(cl::vector& container) +{ + return enqueueUnmapSVM(container); +} + +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + +#if CL_HPP_TARGET_OPENCL_VERSION >= 110 +inline cl_int enqueueReadBufferRect( + const Buffer& buffer, + cl_bool blocking, + const array& buffer_offset, + const array& host_offset, + const array& region, + size_type buffer_row_pitch, + size_type buffer_slice_pitch, + size_type host_row_pitch, + size_type host_slice_pitch, + void* ptr, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if(error != CL_SUCCESS) + { + return error; + } + + return queue.enqueueReadBufferRect( + buffer, + blocking, + buffer_offset, + host_offset, + region, + buffer_row_pitch, + buffer_slice_pitch, + host_row_pitch, + host_slice_pitch, + ptr, + events, + event); +} + +inline cl_int enqueueWriteBufferRect( + const Buffer& buffer, + cl_bool blocking, + const array& buffer_offset, + const array& host_offset, + const array& region, + size_type buffer_row_pitch, + size_type buffer_slice_pitch, + size_type host_row_pitch, + size_type host_slice_pitch, + const void* ptr, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if(error != CL_SUCCESS) + { + return error; + } + + return queue.enqueueWriteBufferRect( + buffer, + blocking, + buffer_offset, + host_offset, + region, + buffer_row_pitch, + buffer_slice_pitch, + host_row_pitch, + host_slice_pitch, + ptr, + events, + event); +} + +inline cl_int enqueueCopyBufferRect( + const Buffer& src, + const Buffer& dst, + const array& src_origin, + const array& dst_origin, + const array& region, + size_type src_row_pitch, + size_type src_slice_pitch, + size_type dst_row_pitch, + size_type dst_slice_pitch, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if(error != CL_SUCCESS) + { + return error; + } + + return queue.enqueueCopyBufferRect( + src, + dst, + src_origin, + dst_origin, + region, + src_row_pitch, + src_slice_pitch, + dst_row_pitch, + dst_slice_pitch, + events, + event); +} + +#endif //CL_HPP_TARGET_OPENCL_VERSION >= 110 + +inline cl_int enqueueReadImage( + const Image& image, + cl_bool blocking, + const array& origin, + const array& region, + size_type row_pitch, + size_type slice_pitch, + void* ptr, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if(error != CL_SUCCESS) + { + return error; + } + + return queue.enqueueReadImage( + image, + blocking, + origin, + region, + row_pitch, + slice_pitch, + ptr, + events, + event); +} + +inline cl_int enqueueWriteImage( + const Image& image, + cl_bool blocking, + const array& origin, + const array& region, + size_type row_pitch, + size_type slice_pitch, + const void* ptr, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if(error != CL_SUCCESS) + { + return error; + } + + return queue.enqueueWriteImage( + image, + blocking, + origin, + region, + row_pitch, + slice_pitch, + ptr, + events, + event); +} + +inline cl_int enqueueCopyImage( + const Image& src, + const Image& dst, + const array& src_origin, + const array& dst_origin, + const array& region, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if(error != CL_SUCCESS) + { + return error; + } + + return queue.enqueueCopyImage( + src, + dst, + src_origin, + dst_origin, + region, + events, + event); +} + +inline cl_int enqueueCopyImageToBuffer( + const Image& src, + const Buffer& dst, + const array& src_origin, + const array& region, + size_type dst_offset, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if(error != CL_SUCCESS) + { + return error; + } + + return queue.enqueueCopyImageToBuffer( + src, + dst, + src_origin, + region, + dst_offset, + events, + event); +} + +inline cl_int enqueueCopyBufferToImage( + const Buffer& src, + const Image& dst, + size_type src_offset, + const array& dst_origin, + const array& region, + const vector* events = NULL, + Event* event = NULL) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if(error != CL_SUCCESS) + { + return error; + } + + return queue.enqueueCopyBufferToImage( + src, + dst, + src_offset, + dst_origin, + region, + events, + event); +} + +inline cl_int flush(void) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if(error != CL_SUCCESS) + { + return error; + } + + return queue.flush(); +} + +inline cl_int finish(void) +{ + cl_int error; + CommandQueue queue = CommandQueue::getDefault(&error); + + if(error != CL_SUCCESS) + { + return error; + } + + return queue.finish(); +} + +class EnqueueArgs +{ +private: + CommandQueue queue_; + const NDRange offset_; + const NDRange global_; + const NDRange local_; + vector events_; + + template + friend class KernelFunctor; + +public: + EnqueueArgs(NDRange global) : + queue_(CommandQueue::getDefault()), + offset_(NullRange), + global_(global), + local_(NullRange) + { + } + + EnqueueArgs(NDRange global, NDRange local) : + queue_(CommandQueue::getDefault()), + offset_(NullRange), + global_(global), + local_(local) + { + } + + EnqueueArgs(NDRange offset, NDRange global, NDRange local) : + queue_(CommandQueue::getDefault()), + offset_(offset), + global_(global), + local_(local) + { + } + + EnqueueArgs(Event e, NDRange global) : + queue_(CommandQueue::getDefault()), + offset_(NullRange), + global_(global), + local_(NullRange) + { + events_.push_back(e); + } + + EnqueueArgs(Event e, NDRange global, NDRange local) : + queue_(CommandQueue::getDefault()), + offset_(NullRange), + global_(global), + local_(local) + { + events_.push_back(e); + } + + EnqueueArgs(Event e, NDRange offset, NDRange global, NDRange local) : + queue_(CommandQueue::getDefault()), + offset_(offset), + global_(global), + local_(local) + { + events_.push_back(e); + } + + EnqueueArgs(const vector& events, NDRange global) : + queue_(CommandQueue::getDefault()), + offset_(NullRange), + global_(global), + local_(NullRange), + events_(events) + { + } + + EnqueueArgs(const vector& events, NDRange global, NDRange local) : + queue_(CommandQueue::getDefault()), + offset_(NullRange), + global_(global), + local_(local), + events_(events) + { + } + + EnqueueArgs(const vector& events, NDRange offset, NDRange global, NDRange local) : + queue_(CommandQueue::getDefault()), + offset_(offset), + global_(global), + local_(local), + events_(events) + { + } + + EnqueueArgs(CommandQueue& queue, NDRange global) : + queue_(queue), + offset_(NullRange), + global_(global), + local_(NullRange) + { + } + + EnqueueArgs(CommandQueue& queue, NDRange global, NDRange local) : + queue_(queue), + offset_(NullRange), + global_(global), + local_(local) + { + } + + EnqueueArgs(CommandQueue& queue, NDRange offset, NDRange global, NDRange local) : + queue_(queue), + offset_(offset), + global_(global), + local_(local) + { + } + + EnqueueArgs(CommandQueue& queue, Event e, NDRange global) : + queue_(queue), + offset_(NullRange), + global_(global), + local_(NullRange) + { + events_.push_back(e); + } + + EnqueueArgs(CommandQueue& queue, Event e, NDRange global, NDRange local) : + queue_(queue), + offset_(NullRange), + global_(global), + local_(local) + { + events_.push_back(e); + } + + EnqueueArgs(CommandQueue& queue, Event e, NDRange offset, NDRange global, NDRange local) : + queue_(queue), + offset_(offset), + global_(global), + local_(local) + { + events_.push_back(e); + } + + EnqueueArgs(CommandQueue& queue, const vector& events, NDRange global) : + queue_(queue), + offset_(NullRange), + global_(global), + local_(NullRange), + events_(events) + { + } + + EnqueueArgs(CommandQueue& queue, const vector& events, NDRange global, NDRange local) : + queue_(queue), + offset_(NullRange), + global_(global), + local_(local), + events_(events) + { + } + + EnqueueArgs(CommandQueue& queue, + const vector& events, + NDRange offset, + NDRange global, + NDRange local) : + queue_(queue), + offset_(offset), + global_(global), + local_(local), + events_(events) + { + } +}; + +//---------------------------------------------------------------------------------------------- + +/** + * Type safe kernel functor. + * + */ +template +class KernelFunctor +{ +private: + Kernel kernel_; + + template + void setArgs(T0&& t0, T1s&&... t1s) + { + kernel_.setArg(index, t0); + setArgs(std::forward(t1s) ...); + } + + template + void setArgs(T0&& t0) + { + kernel_.setArg(index, t0); + } + + template + void setArgs() + { + } + +public: + KernelFunctor(Kernel kernel) : kernel_(kernel) + { + } + + KernelFunctor( + const Program& program, + const string name, + cl_int* err = NULL) : + kernel_(program, name.c_str(), err) + { + } + + //! \brief Return type of the functor + typedef Event result_type; + + /** + * Enqueue kernel. + * @param args Launch parameters of the kernel. + * @param t0... List of kernel arguments based on the template type of the functor. + */ + Event operator() ( + const EnqueueArgs& args, + Ts... ts) + { + Event event; + setArgs<0>(std::forward(ts) ...); + + args.queue_.enqueueNDRangeKernel( + kernel_, + args.offset_, + args.global_, + args.local_, + &args.events_, + &event); + + return event; + } + + /** + * Enqueue kernel with support for error code. + * @param args Launch parameters of the kernel. + * @param t0... List of kernel arguments based on the template type of the functor. + * @param error Out parameter returning the error code from the execution. + */ + Event operator() ( + const EnqueueArgs& args, + Ts... ts, + cl_int& error) + { + Event event; + setArgs<0>(std::forward(ts) ...); + + error = args.queue_.enqueueNDRangeKernel( + kernel_, + args.offset_, + args.global_, + args.local_, + &args.events_, + &event); + + return event; + } + +#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + cl_int setSVMPointers(const vector& pointerList) + { + return kernel_.setSVMPointers(pointerList); + } + + template + cl_int setSVMPointers(const T0& t0, T1s... ts) + { + return kernel_.setSVMPointers(t0, ts ...); + } + +#endif //#if CL_HPP_TARGET_OPENCL_VERSION >= 200 + + Kernel getKernel() + { + return kernel_; + } +}; + +namespace compatibility { +/** + * Backward compatibility class to ensure that cl.hpp code works with cl2.hpp. + * Please use KernelFunctor directly. + */ +template +struct make_kernel +{ + typedef KernelFunctor FunctorType; + + FunctorType functor_; + + make_kernel( + const Program& program, + const string name, + cl_int* err = NULL) : + functor_(FunctorType(program, name, err)) + { + } + + make_kernel( + const Kernel kernel) : + functor_(FunctorType(kernel)) + { + } + + //! \brief Return type of the functor + typedef Event result_type; + + //! \brief Function signature of kernel functor with no event dependency. + typedef Event type_( + const EnqueueArgs&, + Ts...); + + Event operator()( + const EnqueueArgs& enqueueArgs, + Ts... args) + { + return functor_( + enqueueArgs, args ...); + } +}; +} //namespace compatibility + +//---------------------------------------------------------------------------------------------------------------------- + +#undef CL_HPP_ERR_STR_ +#if !defined(CL_HPP_USER_OVERRIDE_ERROR_STRINGS) +#undef __GET_DEVICE_INFO_ERR +#undef __GET_PLATFORM_INFO_ERR +#undef __GET_DEVICE_IDS_ERR +#undef __GET_CONTEXT_INFO_ERR +#undef __GET_EVENT_INFO_ERR +#undef __GET_EVENT_PROFILE_INFO_ERR +#undef __GET_MEM_OBJECT_INFO_ERR +#undef __GET_IMAGE_INFO_ERR +#undef __GET_SAMPLER_INFO_ERR +#undef __GET_KERNEL_INFO_ERR +#undef __GET_KERNEL_ARG_INFO_ERR +#undef __GET_KERNEL_WORK_GROUP_INFO_ERR +#undef __GET_PROGRAM_INFO_ERR +#undef __GET_PROGRAM_BUILD_INFO_ERR +#undef __GET_COMMAND_QUEUE_INFO_ERR + +#undef __CREATE_CONTEXT_ERR +#undef __CREATE_CONTEXT_FROM_TYPE_ERR +#undef __GET_SUPPORTED_IMAGE_FORMATS_ERR + +#undef __CREATE_BUFFER_ERR +#undef __CREATE_SUBBUFFER_ERR +#undef __CREATE_IMAGE2D_ERR +#undef __CREATE_IMAGE3D_ERR +#undef __CREATE_SAMPLER_ERR +#undef __SET_MEM_OBJECT_DESTRUCTOR_CALLBACK_ERR + +#undef __CREATE_USER_EVENT_ERR +#undef __SET_USER_EVENT_STATUS_ERR +#undef __SET_EVENT_CALLBACK_ERR +#undef __SET_PRINTF_CALLBACK_ERR + +#undef __WAIT_FOR_EVENTS_ERR + +#undef __CREATE_KERNEL_ERR +#undef __SET_KERNEL_ARGS_ERR +#undef __CREATE_PROGRAM_WITH_SOURCE_ERR +#undef __CREATE_PROGRAM_WITH_BINARY_ERR +#undef __CREATE_PROGRAM_WITH_BUILT_IN_KERNELS_ERR +#undef __BUILD_PROGRAM_ERR +#undef __CREATE_KERNELS_IN_PROGRAM_ERR + +#undef __CREATE_COMMAND_QUEUE_ERR +#undef __SET_COMMAND_QUEUE_PROPERTY_ERR +#undef __ENQUEUE_READ_BUFFER_ERR +#undef __ENQUEUE_WRITE_BUFFER_ERR +#undef __ENQUEUE_READ_BUFFER_RECT_ERR +#undef __ENQUEUE_WRITE_BUFFER_RECT_ERR +#undef __ENQEUE_COPY_BUFFER_ERR +#undef __ENQEUE_COPY_BUFFER_RECT_ERR +#undef __ENQUEUE_READ_IMAGE_ERR +#undef __ENQUEUE_WRITE_IMAGE_ERR +#undef __ENQUEUE_COPY_IMAGE_ERR +#undef __ENQUEUE_COPY_IMAGE_TO_BUFFER_ERR +#undef __ENQUEUE_COPY_BUFFER_TO_IMAGE_ERR +#undef __ENQUEUE_MAP_BUFFER_ERR +#undef __ENQUEUE_MAP_IMAGE_ERR +#undef __ENQUEUE_UNMAP_MEM_OBJECT_ERR +#undef __ENQUEUE_NDRANGE_KERNEL_ERR +#undef __ENQUEUE_TASK_ERR +#undef __ENQUEUE_NATIVE_KERNEL + +#undef __UNLOAD_COMPILER_ERR +#undef __CREATE_SUB_DEVICES_ERR + +#undef __CREATE_PIPE_ERR +#undef __GET_PIPE_INFO_ERR + +#endif //CL_HPP_USER_OVERRIDE_ERROR_STRINGS + +//Extensions +#undef CL_HPP_INIT_CL_EXT_FCN_PTR_ +#undef CL_HPP_INIT_CL_EXT_FCN_PTR_PLATFORM_ + +#if defined(CL_HPP_USE_CL_DEVICE_FISSION) +#undef CL_HPP_PARAM_NAME_DEVICE_FISSION_ +#endif //CL_HPP_USE_CL_DEVICE_FISSION + +#undef CL_HPP_NOEXCEPT_ +#undef CL_HPP_DEFINE_STATIC_MEMBER_ +} //namespace cl + +#endif //CL_HPP_ diff --git a/include/lib/CL/cl_d3d10.h b/include/lib/CL/cl_d3d10.h new file mode 100644 index 0000000..070a4c7 --- /dev/null +++ b/include/lib/CL/cl_d3d10.h @@ -0,0 +1,126 @@ +/********************************************************************************** + * Copyright (c) 2008-2012 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + **********************************************************************************/ + +/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ + +#ifndef __OPENCL_CL_D3D10_H +#define __OPENCL_CL_D3D10_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/****************************************************************************** + * cl_khr_d3d10_sharing */ +#define cl_khr_d3d10_sharing 1 + +typedef cl_uint cl_d3d10_device_source_khr; +typedef cl_uint cl_d3d10_device_set_khr; + +/******************************************************************************/ + +/* Error Codes */ +#define CL_INVALID_D3D10_DEVICE_KHR -1002 +#define CL_INVALID_D3D10_RESOURCE_KHR -1003 +#define CL_D3D10_RESOURCE_ALREADY_ACQUIRED_KHR -1004 +#define CL_D3D10_RESOURCE_NOT_ACQUIRED_KHR -1005 + +/* cl_d3d10_device_source_nv */ +#define CL_D3D10_DEVICE_KHR 0x4010 +#define CL_D3D10_DXGI_ADAPTER_KHR 0x4011 + +/* cl_d3d10_device_set_nv */ +#define CL_PREFERRED_DEVICES_FOR_D3D10_KHR 0x4012 +#define CL_ALL_DEVICES_FOR_D3D10_KHR 0x4013 + +/* cl_context_info */ +#define CL_CONTEXT_D3D10_DEVICE_KHR 0x4014 +#define CL_CONTEXT_D3D10_PREFER_SHARED_RESOURCES_KHR 0x402C + +/* cl_mem_info */ +#define CL_MEM_D3D10_RESOURCE_KHR 0x4015 + +/* cl_image_info */ +#define CL_IMAGE_D3D10_SUBRESOURCE_KHR 0x4016 + +/* cl_command_type */ +#define CL_COMMAND_ACQUIRE_D3D10_OBJECTS_KHR 0x4017 +#define CL_COMMAND_RELEASE_D3D10_OBJECTS_KHR 0x4018 + +/******************************************************************************/ + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceIDsFromD3D10KHR_fn)( + cl_platform_id platform, + cl_d3d10_device_source_khr d3d_device_source, + void * d3d_object, + cl_d3d10_device_set_khr d3d_device_set, + cl_uint num_entries, + cl_device_id * devices, + cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D10BufferKHR_fn)( + cl_context context, + cl_mem_flags flags, + ID3D10Buffer * resource, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D10Texture2DKHR_fn)( + cl_context context, + cl_mem_flags flags, + ID3D10Texture2D * resource, + UINT subresource, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D10Texture3DKHR_fn)( + cl_context context, + cl_mem_flags flags, + ID3D10Texture3D * resource, + UINT subresource, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireD3D10ObjectsKHR_fn)( + cl_command_queue command_queue, + cl_uint num_objects, + const cl_mem * mem_objects, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseD3D10ObjectsKHR_fn)( + cl_command_queue command_queue, + cl_uint num_objects, + const cl_mem * mem_objects, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +#ifdef __cplusplus +} +#endif + +#endif /* __OPENCL_CL_D3D10_H */ + diff --git a/include/lib/CL/cl_d3d10_ext.h b/include/lib/CL/cl_d3d10_ext.h new file mode 100644 index 0000000..4198be2 --- /dev/null +++ b/include/lib/CL/cl_d3d10_ext.h @@ -0,0 +1,122 @@ +/********************************************************************************** + * Copyright (c) 2008-2009 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + **********************************************************************************/ + +#ifndef __OPENCL_CL_D3D10_EXT_H +#define __OPENCL_CL_D3D10_EXT_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/****************************************************************************** + * cl_nv_d3d10_sharing */ + +typedef cl_uint cl_d3d10_device_source_nv; +typedef cl_uint cl_d3d10_device_set_nv; + +/******************************************************************************/ + +// Error Codes +#define CL_INVALID_D3D10_DEVICE_NV -1002 +#define CL_INVALID_D3D10_RESOURCE_NV -1003 +#define CL_D3D10_RESOURCE_ALREADY_ACQUIRED_NV -1004 +#define CL_D3D10_RESOURCE_NOT_ACQUIRED_NV -1005 + +// cl_d3d10_device_source_nv +#define CL_D3D10_DEVICE_NV 0x4010 +#define CL_D3D10_DXGI_ADAPTER_NV 0x4011 + +// cl_d3d10_device_set_nv +#define CL_PREFERRED_DEVICES_FOR_D3D10_NV 0x4012 +#define CL_ALL_DEVICES_FOR_D3D10_NV 0x4013 + +// cl_context_info +#define CL_CONTEXT_D3D10_DEVICE_NV 0x4014 + +// cl_mem_info +#define CL_MEM_D3D10_RESOURCE_NV 0x4015 + +// cl_image_info +#define CL_IMAGE_D3D10_SUBRESOURCE_NV 0x4016 + +// cl_command_type +#define CL_COMMAND_ACQUIRE_D3D10_OBJECTS_NV 0x4017 +#define CL_COMMAND_RELEASE_D3D10_OBJECTS_NV 0x4018 + +/******************************************************************************/ + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceIDsFromD3D10NV_fn)( + cl_platform_id platform, + cl_d3d10_device_source_nv d3d_device_source, + void * d3d_object, + cl_d3d10_device_set_nv d3d_device_set, + cl_uint num_entries, + cl_device_id * devices, + cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D10BufferNV_fn)( + cl_context context, + cl_mem_flags flags, + ID3D10Buffer * resource, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D10Texture2DNV_fn)( + cl_context context, + cl_mem_flags flags, + ID3D10Texture2D * resource, + UINT subresource, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D10Texture3DNV_fn)( + cl_context context, + cl_mem_flags flags, + ID3D10Texture3D * resource, + UINT subresource, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireD3D10ObjectsNV_fn)( + cl_command_queue command_queue, + cl_uint num_objects, + const cl_mem * mem_objects, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseD3D10ObjectsNV_fn)( + cl_command_queue command_queue, + cl_uint num_objects, + cl_mem * mem_objects, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +#ifdef __cplusplus +} +#endif + +#endif // __OPENCL_CL_D3D10_H + diff --git a/include/lib/CL/cl_d3d11.h b/include/lib/CL/cl_d3d11.h new file mode 100644 index 0000000..33634cb --- /dev/null +++ b/include/lib/CL/cl_d3d11.h @@ -0,0 +1,126 @@ +/********************************************************************************** + * Copyright (c) 2008-2012 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + **********************************************************************************/ + +/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ + +#ifndef __OPENCL_CL_D3D11_H +#define __OPENCL_CL_D3D11_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/****************************************************************************** + * cl_khr_d3d11_sharing */ +#define cl_khr_d3d11_sharing 1 + +typedef cl_uint cl_d3d11_device_source_khr; +typedef cl_uint cl_d3d11_device_set_khr; + +/******************************************************************************/ + +/* Error Codes */ +#define CL_INVALID_D3D11_DEVICE_KHR -1006 +#define CL_INVALID_D3D11_RESOURCE_KHR -1007 +#define CL_D3D11_RESOURCE_ALREADY_ACQUIRED_KHR -1008 +#define CL_D3D11_RESOURCE_NOT_ACQUIRED_KHR -1009 + +/* cl_d3d11_device_source */ +#define CL_D3D11_DEVICE_KHR 0x4019 +#define CL_D3D11_DXGI_ADAPTER_KHR 0x401A + +/* cl_d3d11_device_set */ +#define CL_PREFERRED_DEVICES_FOR_D3D11_KHR 0x401B +#define CL_ALL_DEVICES_FOR_D3D11_KHR 0x401C + +/* cl_context_info */ +#define CL_CONTEXT_D3D11_DEVICE_KHR 0x401D +#define CL_CONTEXT_D3D11_PREFER_SHARED_RESOURCES_KHR 0x402D + +/* cl_mem_info */ +#define CL_MEM_D3D11_RESOURCE_KHR 0x401E + +/* cl_image_info */ +#define CL_IMAGE_D3D11_SUBRESOURCE_KHR 0x401F + +/* cl_command_type */ +#define CL_COMMAND_ACQUIRE_D3D11_OBJECTS_KHR 0x4020 +#define CL_COMMAND_RELEASE_D3D11_OBJECTS_KHR 0x4021 + +/******************************************************************************/ + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceIDsFromD3D11KHR_fn)( + cl_platform_id platform, + cl_d3d11_device_source_khr d3d_device_source, + void * d3d_object, + cl_d3d11_device_set_khr d3d_device_set, + cl_uint num_entries, + cl_device_id * devices, + cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D11BufferKHR_fn)( + cl_context context, + cl_mem_flags flags, + ID3D11Buffer * resource, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D11Texture2DKHR_fn)( + cl_context context, + cl_mem_flags flags, + ID3D11Texture2D * resource, + UINT subresource, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D11Texture3DKHR_fn)( + cl_context context, + cl_mem_flags flags, + ID3D11Texture3D * resource, + UINT subresource, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireD3D11ObjectsKHR_fn)( + cl_command_queue command_queue, + cl_uint num_objects, + const cl_mem * mem_objects, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseD3D11ObjectsKHR_fn)( + cl_command_queue command_queue, + cl_uint num_objects, + const cl_mem * mem_objects, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_2; + +#ifdef __cplusplus +} +#endif + +#endif /* __OPENCL_CL_D3D11_H */ + diff --git a/include/lib/CL/cl_d3d11_ext.h b/include/lib/CL/cl_d3d11_ext.h new file mode 100644 index 0000000..96e9b28 --- /dev/null +++ b/include/lib/CL/cl_d3d11_ext.h @@ -0,0 +1,122 @@ +/********************************************************************************** + * Copyright (c) 2008-2009 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + **********************************************************************************/ + +#ifndef __OPENCL_CL_D3D11_EXT_H +#define __OPENCL_CL_D3D11_EXT_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/****************************************************************************** + * cl_nv_d3d11_sharing */ + +typedef cl_uint cl_d3d11_device_source_nv; +typedef cl_uint cl_d3d11_device_set_nv; + +/******************************************************************************/ + +// Error Codes +#define CL_INVALID_D3D11_DEVICE_NV -1006 +#define CL_INVALID_D3D11_RESOURCE_NV -1007 +#define CL_D3D11_RESOURCE_ALREADY_ACQUIRED_NV -1008 +#define CL_D3D11_RESOURCE_NOT_ACQUIRED_NV -1009 + +// cl_d3d11_device_source_nv +#define CL_D3D11_DEVICE_NV 0x4019 +#define CL_D3D11_DXGI_ADAPTER_NV 0x401A + +// cl_d3d11_device_set_nv +#define CL_PREFERRED_DEVICES_FOR_D3D11_NV 0x401B +#define CL_ALL_DEVICES_FOR_D3D11_NV 0x401C + +// cl_context_info +#define CL_CONTEXT_D3D11_DEVICE_NV 0x401D + +// cl_mem_info +#define CL_MEM_D3D11_RESOURCE_NV 0x401E + +// cl_image_info +#define CL_IMAGE_D3D11_SUBRESOURCE_NV 0x401F + +// cl_command_type +#define CL_COMMAND_ACQUIRE_D3D11_OBJECTS_NV 0x4020 +#define CL_COMMAND_RELEASE_D3D11_OBJECTS_NV 0x4021 + +/******************************************************************************/ + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceIDsFromD3D11NV_fn)( + cl_platform_id platform, + cl_d3d11_device_source_nv d3d_device_source, + void * d3d_object, + cl_d3d11_device_set_nv d3d_device_set, + cl_uint num_entries, + cl_device_id * devices, + cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D11BufferNV_fn)( + cl_context context, + cl_mem_flags flags, + ID3D11Buffer * resource, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D11Texture2DNV_fn)( + cl_context context, + cl_mem_flags flags, + ID3D11Texture2D * resource, + UINT subresource, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D11Texture3DNV_fn)( + cl_context context, + cl_mem_flags flags, + ID3D11Texture3D * resource, + UINT subresource, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireD3D11ObjectsNV_fn)( + cl_command_queue command_queue, + cl_uint num_objects, + const cl_mem * mem_objects, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseD3D11ObjectsNV_fn)( + cl_command_queue command_queue, + cl_uint num_objects, + cl_mem * mem_objects, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_0; + +#ifdef __cplusplus +} +#endif + +#endif // __OPENCL_CL_D3D11_H + diff --git a/include/lib/CL/cl_d3d9_ext.h b/include/lib/CL/cl_d3d9_ext.h new file mode 100644 index 0000000..4cbee65 --- /dev/null +++ b/include/lib/CL/cl_d3d9_ext.h @@ -0,0 +1,143 @@ +/********************************************************************************** + * Copyright (c) 2008-2009 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + **********************************************************************************/ + +#ifndef __OPENCL_CL_D3D9_EXT_H +#define __OPENCL_CL_D3D9_EXT_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/****************************************************************************** + * cl_nv_d3d9_sharing */ + +typedef cl_uint cl_d3d9_device_source_nv; +typedef cl_uint cl_d3d9_device_set_nv; + +/******************************************************************************/ + +// Error Codes +#define CL_INVALID_D3D9_DEVICE_NV -1010 +#define CL_INVALID_D3D9_RESOURCE_NV -1011 +#define CL_D3D9_RESOURCE_ALREADY_ACQUIRED_NV -1012 +#define CL_D3D9_RESOURCE_NOT_ACQUIRED_NV -1013 + +// cl_d3d9_device_source_nv +#define CL_D3D9_DEVICE_NV 0x4022 +#define CL_D3D9_ADAPTER_NAME_NV 0x4023 + +// cl_d3d9_device_set_nv +#define CL_PREFERRED_DEVICES_FOR_D3D9_NV 0x4024 +#define CL_ALL_DEVICES_FOR_D3D9_NV 0x4025 + +// cl_context_info +#define CL_CONTEXT_D3D9_DEVICE_NV 0x4026 + +// cl_mem_info +#define CL_MEM_D3D9_RESOURCE_NV 0x4027 + +// cl_image_info +#define CL_IMAGE_D3D9_FACE_NV 0x4028 +#define CL_IMAGE_D3D9_LEVEL_NV 0x4029 + +// cl_command_type +#define CL_COMMAND_ACQUIRE_D3D9_OBJECTS_NV 0x402A +#define CL_COMMAND_RELEASE_D3D9_OBJECTS_NV 0x402B + +/******************************************************************************/ + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceIDsFromD3D9NV_fn)( + cl_platform_id platform, + cl_d3d9_device_source_nv d3d_device_source, + void * d3d_object, + cl_d3d9_device_set_nv d3d_device_set, + cl_uint num_entries, + cl_device_id * devices, + cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D9VertexBufferNV_fn)( + cl_context context, + cl_mem_flags flags, + IDirect3DVertexBuffer9 * resource, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D9IndexBufferNV_fn)( + cl_context context, + cl_mem_flags flags, + IDirect3DIndexBuffer9 * resource, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D9SurfaceNV_fn)( + cl_context context, + cl_mem_flags flags, + IDirect3DSurface9 * resource, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D9TextureNV_fn)( + cl_context context, + cl_mem_flags flags, + IDirect3DTexture9 *resource, + UINT miplevel, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D9CubeTextureNV_fn)( + cl_context context, + cl_mem_flags flags, + IDirect3DCubeTexture9 * resource, + D3DCUBEMAP_FACES facetype, + UINT miplevel, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D9VolumeTextureNV_fn)( + cl_context context, + cl_mem_flags flags, + IDirect3DVolumeTexture9 * resource, + UINT miplevel, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireD3D9ObjectsNV_fn)( + cl_command_queue command_queue, + cl_uint num_objects, + const cl_mem *mem_objects, + cl_uint num_events_in_wait_list, + const cl_event *event_wait_list, + cl_event *event) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseD3D9ObjectsNV_fn)( + cl_command_queue command_queue, + cl_uint num_objects, + cl_mem *mem_objects, + cl_uint num_events_in_wait_list, + const cl_event *event_wait_list, + cl_event *event) CL_API_SUFFIX__VERSION_1_0; + +#ifdef __cplusplus +} +#endif + +#endif // __OPENCL_CL_D3D9_H + diff --git a/include/lib/CL/cl_dx9_media_sharing.h b/include/lib/CL/cl_dx9_media_sharing.h new file mode 100644 index 0000000..4d1b3d1 --- /dev/null +++ b/include/lib/CL/cl_dx9_media_sharing.h @@ -0,0 +1,127 @@ +/********************************************************************************** + * Copyright (c) 2008-2012 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + **********************************************************************************/ + +/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ + +#ifndef __OPENCL_CL_DX9_MEDIA_SHARING_H +#define __OPENCL_CL_DX9_MEDIA_SHARING_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/****************************************************************************** +/* cl_khr_dx9_media_sharing */ +#define cl_khr_dx9_media_sharing 1 + +typedef cl_uint cl_dx9_media_adapter_type_khr; +typedef cl_uint cl_dx9_media_adapter_set_khr; + +#if defined(_WIN32) +#include +typedef struct _cl_dx9_surface_info_khr +{ + IDirect3DSurface9 *resource; + HANDLE shared_handle; +} cl_dx9_surface_info_khr; +#endif + + +/******************************************************************************/ + +/* Error Codes */ +#define CL_INVALID_DX9_MEDIA_ADAPTER_KHR -1010 +#define CL_INVALID_DX9_MEDIA_SURFACE_KHR -1011 +#define CL_DX9_MEDIA_SURFACE_ALREADY_ACQUIRED_KHR -1012 +#define CL_DX9_MEDIA_SURFACE_NOT_ACQUIRED_KHR -1013 + +/* cl_media_adapter_type_khr */ +#define CL_ADAPTER_D3D9_KHR 0x2020 +#define CL_ADAPTER_D3D9EX_KHR 0x2021 +#define CL_ADAPTER_DXVA_KHR 0x2022 + +/* cl_media_adapter_set_khr */ +#define CL_PREFERRED_DEVICES_FOR_DX9_MEDIA_ADAPTER_KHR 0x2023 +#define CL_ALL_DEVICES_FOR_DX9_MEDIA_ADAPTER_KHR 0x2024 + +/* cl_context_info */ +#define CL_CONTEXT_ADAPTER_D3D9_KHR 0x2025 +#define CL_CONTEXT_ADAPTER_D3D9EX_KHR 0x2026 +#define CL_CONTEXT_ADAPTER_DXVA_KHR 0x2027 + +/* cl_mem_info */ +#define CL_MEM_DX9_MEDIA_ADAPTER_TYPE_KHR 0x2028 +#define CL_MEM_DX9_MEDIA_SURFACE_INFO_KHR 0x2029 + +/* cl_image_info */ +#define CL_IMAGE_DX9_MEDIA_PLANE_KHR 0x202A + +/* cl_command_type */ +#define CL_COMMAND_ACQUIRE_DX9_MEDIA_SURFACES_KHR 0x202B +#define CL_COMMAND_RELEASE_DX9_MEDIA_SURFACES_KHR 0x202C + +/******************************************************************************/ + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceIDsFromDX9MediaAdapterKHR_fn)( + cl_platform_id platform, + cl_uint num_media_adapters, + cl_dx9_media_adapter_type_khr * media_adapter_type, + void * media_adapters, + cl_dx9_media_adapter_set_khr media_adapter_set, + cl_uint num_entries, + cl_device_id * devices, + cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromDX9MediaSurfaceKHR_fn)( + cl_context context, + cl_mem_flags flags, + cl_dx9_media_adapter_type_khr adapter_type, + void * surface_info, + cl_uint plane, + cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireDX9MediaSurfacesKHR_fn)( + cl_command_queue command_queue, + cl_uint num_objects, + const cl_mem * mem_objects, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseDX9MediaSurfacesKHR_fn)( + cl_command_queue command_queue, + cl_uint num_objects, + const cl_mem * mem_objects, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event) CL_API_SUFFIX__VERSION_1_2; + +#ifdef __cplusplus +} +#endif + +#endif /* __OPENCL_CL_DX9_MEDIA_SHARING_H */ + diff --git a/include/lib/CL/cl_egl.h b/include/lib/CL/cl_egl.h new file mode 100644 index 0000000..ce8e826 --- /dev/null +++ b/include/lib/CL/cl_egl.h @@ -0,0 +1,133 @@ +/******************************************************************************* + * Copyright (c) 2008-2010 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + ******************************************************************************/ + +#ifndef __OPENCL_CL_EGL_H +#define __OPENCL_CL_EGL_H + +#ifdef __APPLE__ + +#else +#include +#include +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + + +/* Command type for events created with clEnqueueAcquireEGLObjectsKHR */ +#define CL_COMMAND_EGL_FENCE_SYNC_OBJECT_KHR 0x202F +#define CL_COMMAND_ACQUIRE_EGL_OBJECTS_KHR 0x202D +#define CL_COMMAND_RELEASE_EGL_OBJECTS_KHR 0x202E + +/* Error type for clCreateFromEGLImageKHR */ +#define CL_INVALID_EGL_OBJECT_KHR -1093 +#define CL_EGL_RESOURCE_NOT_ACQUIRED_KHR -1092 + +/* CLeglImageKHR is an opaque handle to an EGLImage */ +typedef void* CLeglImageKHR; + +/* CLeglDisplayKHR is an opaque handle to an EGLDisplay */ +typedef void* CLeglDisplayKHR; + +/* CLeglSyncKHR is an opaque handle to an EGLSync object */ +typedef void* CLeglSyncKHR; + +/* properties passed to clCreateFromEGLImageKHR */ +typedef intptr_t cl_egl_image_properties_khr; + + +#define cl_khr_egl_image 1 + +extern CL_API_ENTRY cl_mem CL_API_CALL +clCreateFromEGLImageKHR(cl_context /* context */, + CLeglDisplayKHR /* egldisplay */, + CLeglImageKHR /* eglimage */, + cl_mem_flags /* flags */, + const cl_egl_image_properties_khr * /* properties */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromEGLImageKHR_fn)( + cl_context context, + CLeglDisplayKHR egldisplay, + CLeglImageKHR eglimage, + cl_mem_flags flags, + const cl_egl_image_properties_khr * properties, + cl_int * errcode_ret); + + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueAcquireEGLObjectsKHR(cl_command_queue /* command_queue */, + cl_uint /* num_objects */, + const cl_mem * /* mem_objects */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireEGLObjectsKHR_fn)( + cl_command_queue command_queue, + cl_uint num_objects, + const cl_mem * mem_objects, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event); + + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueReleaseEGLObjectsKHR(cl_command_queue /* command_queue */, + cl_uint /* num_objects */, + const cl_mem * /* mem_objects */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseEGLObjectsKHR_fn)( + cl_command_queue command_queue, + cl_uint num_objects, + const cl_mem * mem_objects, + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event); + + +#define cl_khr_egl_event 1 + +extern CL_API_ENTRY cl_event CL_API_CALL +clCreateEventFromEGLSyncKHR(cl_context /* context */, + CLeglSyncKHR /* sync */, + CLeglDisplayKHR /* display */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_event (CL_API_CALL *clCreateEventFromEGLSyncKHR_fn)( + cl_context context, + CLeglSyncKHR sync, + CLeglDisplayKHR display, + cl_int * errcode_ret); + +#ifdef __cplusplus +} +#endif + +#endif /* __OPENCL_CL_EGL_H */ diff --git a/include/lib/CL/cl_ext.h b/include/lib/CL/cl_ext.h new file mode 100644 index 0000000..56153f4 --- /dev/null +++ b/include/lib/CL/cl_ext.h @@ -0,0 +1,334 @@ +/******************************************************************************* + * Copyright (c) 2008-2013 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + ******************************************************************************/ + +/* $Revision: 11928 $ on $Date: 2010-07-13 09:04:56 -0700 (Tue, 13 Jul 2010) $ */ + +/* cl_ext.h contains OpenCL extensions which don't have external */ +/* (OpenGL, D3D) dependencies. */ + +#ifndef __CL_EXT_H +#define __CL_EXT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __APPLE__ + #include + #include +#else + #include +#endif + +/* cl_khr_fp16 extension - no extension #define since it has no functions */ +#define CL_DEVICE_HALF_FP_CONFIG 0x1033 + +/* Memory object destruction + * + * Apple extension for use to manage externally allocated buffers used with cl_mem objects with CL_MEM_USE_HOST_PTR + * + * Registers a user callback function that will be called when the memory object is deleted and its resources + * freed. Each call to clSetMemObjectCallbackFn registers the specified user callback function on a callback + * stack associated with memobj. The registered user callback functions are called in the reverse order in + * which they were registered. The user callback functions are called and then the memory object is deleted + * and its resources freed. This provides a mechanism for the application (and libraries) using memobj to be + * notified when the memory referenced by host_ptr, specified when the memory object is created and used as + * the storage bits for the memory object, can be reused or freed. + * + * The application may not call CL api's with the cl_mem object passed to the pfn_notify. + * + * Please check for the "cl_APPLE_SetMemObjectDestructor" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS) + * before using. + */ +#define cl_APPLE_SetMemObjectDestructor 1 +cl_int CL_API_ENTRY clSetMemObjectDestructorAPPLE( cl_mem /* memobj */, + void (* /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/), + void * /*user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; + + +/* Context Logging Functions + * + * The next three convenience functions are intended to be used as the pfn_notify parameter to clCreateContext(). + * Please check for the "cl_APPLE_ContextLoggingFunctions" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS) + * before using. + * + * clLogMessagesToSystemLog fowards on all log messages to the Apple System Logger + */ +#define cl_APPLE_ContextLoggingFunctions 1 +extern void CL_API_ENTRY clLogMessagesToSystemLogAPPLE( const char * /* errstr */, + const void * /* private_info */, + size_t /* cb */, + void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; + +/* clLogMessagesToStdout sends all log messages to the file descriptor stdout */ +extern void CL_API_ENTRY clLogMessagesToStdoutAPPLE( const char * /* errstr */, + const void * /* private_info */, + size_t /* cb */, + void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; + +/* clLogMessagesToStderr sends all log messages to the file descriptor stderr */ +extern void CL_API_ENTRY clLogMessagesToStderrAPPLE( const char * /* errstr */, + const void * /* private_info */, + size_t /* cb */, + void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0; + + +/************************ +* cl_khr_icd extension * +************************/ +#define cl_khr_icd 1 + +/* cl_platform_info */ +#define CL_PLATFORM_ICD_SUFFIX_KHR 0x0920 + +/* Additional Error Codes */ +#define CL_PLATFORM_NOT_FOUND_KHR -1001 + +extern CL_API_ENTRY cl_int CL_API_CALL +clIcdGetPlatformIDsKHR(cl_uint /* num_entries */, + cl_platform_id * /* platforms */, + cl_uint * /* num_platforms */); + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clIcdGetPlatformIDsKHR_fn)( + cl_uint /* num_entries */, + cl_platform_id * /* platforms */, + cl_uint * /* num_platforms */); + + +/* Extension: cl_khr_image2D_buffer + * + * This extension allows a 2D image to be created from a cl_mem buffer without a copy. + * The type associated with a 2D image created from a buffer in an OpenCL program is image2d_t. + * Both the sampler and sampler-less read_image built-in functions are supported for 2D images + * and 2D images created from a buffer. Similarly, the write_image built-ins are also supported + * for 2D images created from a buffer. + * + * When the 2D image from buffer is created, the client must specify the width, + * height, image format (i.e. channel order and channel data type) and optionally the row pitch + * + * The pitch specified must be a multiple of CL_DEVICE_IMAGE_PITCH_ALIGNMENT pixels. + * The base address of the buffer must be aligned to CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT pixels. + */ + +/************************************* + * cl_khr_initalize_memory extension * + *************************************/ + +#define CL_CONTEXT_MEMORY_INITIALIZE_KHR 0x200E + + +/************************************** + * cl_khr_terminate_context extension * + **************************************/ + +#define CL_DEVICE_TERMINATE_CAPABILITY_KHR 0x200F +#define CL_CONTEXT_TERMINATE_KHR 0x2010 + +#define cl_khr_terminate_context 1 +extern CL_API_ENTRY cl_int CL_API_CALL clTerminateContextKHR(cl_context /* context */) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clTerminateContextKHR_fn)(cl_context /* context */) CL_EXT_SUFFIX__VERSION_1_2; + + +/* + * Extension: cl_khr_spir + * + * This extension adds support to create an OpenCL program object from a + * Standard Portable Intermediate Representation (SPIR) instance + */ + +#define CL_DEVICE_SPIR_VERSIONS 0x40E0 +#define CL_PROGRAM_BINARY_TYPE_INTERMEDIATE 0x40E1 + + +/****************************************** +* cl_nv_device_attribute_query extension * +******************************************/ +/* cl_nv_device_attribute_query extension - no extension #define since it has no functions */ +#define CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV 0x4000 +#define CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV 0x4001 +#define CL_DEVICE_REGISTERS_PER_BLOCK_NV 0x4002 +#define CL_DEVICE_WARP_SIZE_NV 0x4003 +#define CL_DEVICE_GPU_OVERLAP_NV 0x4004 +#define CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV 0x4005 +#define CL_DEVICE_INTEGRATED_MEMORY_NV 0x4006 +#define CL_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT_NV 0x4007 +#define CL_DEVICE_PCI_BUS_ID_NV 0x4008 +#define CL_DEVICE_PCI_SLOT_ID_NV 0x4009 + +/****************************************** +* cl_nv_create_buffer extension * +******************************************/ +typedef cl_bitfield cl_mem_flags_NV; + +CL_API_ENTRY cl_mem CL_API_CALL +clCreateBufferNV(cl_context context, + cl_mem_flags flags, + cl_mem_flags_NV flags_NV, + size_t size, + void *host_ptr, + cl_int *errcode_ret); +#define CL_MEM_LOCATION_HOST_NV (1 << 0) +#define CL_MEM_PINNED_NV (1 << 1) + +/********************************* +* cl_amd_device_attribute_query * +*********************************/ +#define CL_DEVICE_PROFILING_TIMER_OFFSET_AMD 0x4036 + +/********************************* +* cl_arm_printf extension +*********************************/ +#define CL_PRINTF_CALLBACK_ARM 0x40B0 +#define CL_PRINTF_BUFFERSIZE_ARM 0x40B1 + +#ifdef CL_VERSION_1_1 + /*********************************** + * cl_ext_device_fission extension * + ***********************************/ + #define cl_ext_device_fission 1 + + extern CL_API_ENTRY cl_int CL_API_CALL + clReleaseDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; + + typedef CL_API_ENTRY cl_int + (CL_API_CALL *clReleaseDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; + + extern CL_API_ENTRY cl_int CL_API_CALL + clRetainDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; + + typedef CL_API_ENTRY cl_int + (CL_API_CALL *clRetainDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1; + + typedef cl_ulong cl_device_partition_property_ext; + extern CL_API_ENTRY cl_int CL_API_CALL + clCreateSubDevicesEXT( cl_device_id /*in_device*/, + const cl_device_partition_property_ext * /* properties */, + cl_uint /*num_entries*/, + cl_device_id * /*out_devices*/, + cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1; + + typedef CL_API_ENTRY cl_int + ( CL_API_CALL * clCreateSubDevicesEXT_fn)( cl_device_id /*in_device*/, + const cl_device_partition_property_ext * /* properties */, + cl_uint /*num_entries*/, + cl_device_id * /*out_devices*/, + cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1; + + /* cl_device_partition_property_ext */ + #define CL_DEVICE_PARTITION_EQUALLY_EXT 0x4050 + #define CL_DEVICE_PARTITION_BY_COUNTS_EXT 0x4051 + #define CL_DEVICE_PARTITION_BY_NAMES_EXT 0x4052 + #define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT 0x4053 + + /* clDeviceGetInfo selectors */ + #define CL_DEVICE_PARENT_DEVICE_EXT 0x4054 + #define CL_DEVICE_PARTITION_TYPES_EXT 0x4055 + #define CL_DEVICE_AFFINITY_DOMAINS_EXT 0x4056 + #define CL_DEVICE_REFERENCE_COUNT_EXT 0x4057 + #define CL_DEVICE_PARTITION_STYLE_EXT 0x4058 + + /* error codes */ + #define CL_DEVICE_PARTITION_FAILED_EXT -1057 + #define CL_INVALID_PARTITION_COUNT_EXT -1058 + #define CL_INVALID_PARTITION_NAME_EXT -1059 + + /* CL_AFFINITY_DOMAINs */ + #define CL_AFFINITY_DOMAIN_L1_CACHE_EXT 0x1 + #define CL_AFFINITY_DOMAIN_L2_CACHE_EXT 0x2 + #define CL_AFFINITY_DOMAIN_L3_CACHE_EXT 0x3 + #define CL_AFFINITY_DOMAIN_L4_CACHE_EXT 0x4 + #define CL_AFFINITY_DOMAIN_NUMA_EXT 0x10 + #define CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT 0x100 + + /* cl_device_partition_property_ext list terminators */ + #define CL_PROPERTIES_LIST_END_EXT ((cl_device_partition_property_ext) 0) + #define CL_PARTITION_BY_COUNTS_LIST_END_EXT ((cl_device_partition_property_ext) 0) + #define CL_PARTITION_BY_NAMES_LIST_END_EXT ((cl_device_partition_property_ext) 0 - 1) + +/********************************* +* cl_qcom_ext_host_ptr extension +*********************************/ + +#define CL_MEM_EXT_HOST_PTR_QCOM (1 << 29) + +#define CL_DEVICE_EXT_MEM_PADDING_IN_BYTES_QCOM 0x40A0 +#define CL_DEVICE_PAGE_SIZE_QCOM 0x40A1 +#define CL_IMAGE_ROW_ALIGNMENT_QCOM 0x40A2 +#define CL_IMAGE_SLICE_ALIGNMENT_QCOM 0x40A3 +#define CL_MEM_HOST_UNCACHED_QCOM 0x40A4 +#define CL_MEM_HOST_WRITEBACK_QCOM 0x40A5 +#define CL_MEM_HOST_WRITETHROUGH_QCOM 0x40A6 +#define CL_MEM_HOST_WRITE_COMBINING_QCOM 0x40A7 + +typedef cl_uint cl_image_pitch_info_qcom; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetDeviceImageInfoQCOM(cl_device_id device, + size_t image_width, + size_t image_height, + const cl_image_format *image_format, + cl_image_pitch_info_qcom param_name, + size_t param_value_size, + void *param_value, + size_t *param_value_size_ret); + +typedef struct _cl_mem_ext_host_ptr +{ + /* Type of external memory allocation. */ + /* Legal values will be defined in layered extensions. */ + cl_uint allocation_type; + + /* Host cache policy for this external memory allocation. */ + cl_uint host_cache_policy; + +} cl_mem_ext_host_ptr; + +/********************************* +* cl_qcom_ion_host_ptr extension +*********************************/ + +#define CL_MEM_ION_HOST_PTR_QCOM 0x40A8 + +typedef struct _cl_mem_ion_host_ptr +{ + /* Type of external memory allocation. */ + /* Must be CL_MEM_ION_HOST_PTR_QCOM for ION allocations. */ + cl_mem_ext_host_ptr ext_host_ptr; + + /* ION file descriptor */ + int ion_filedesc; + + /* Host pointer to the ION allocated memory */ + void* ion_hostptr; + +} cl_mem_ion_host_ptr; + +#endif /* CL_VERSION_1_1 */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __CL_EXT_H */ diff --git a/include/lib/CL/cl_gl.h b/include/lib/CL/cl_gl.h new file mode 100644 index 0000000..63b102a --- /dev/null +++ b/include/lib/CL/cl_gl.h @@ -0,0 +1,162 @@ +/********************************************************************************** + * Copyright (c) 2008 - 2012 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + **********************************************************************************/ + +#ifndef __OPENCL_CL_GL_H +#define __OPENCL_CL_GL_H + +#ifdef __APPLE__ +#include +#else +#include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef cl_uint cl_gl_object_type; +typedef cl_uint cl_gl_texture_info; +typedef cl_uint cl_gl_platform_info; +typedef struct __GLsync *cl_GLsync; + +/* cl_gl_object_type = 0x2000 - 0x200F enum values are currently taken */ +#define CL_GL_OBJECT_BUFFER 0x2000 +#define CL_GL_OBJECT_TEXTURE2D 0x2001 +#define CL_GL_OBJECT_TEXTURE3D 0x2002 +#define CL_GL_OBJECT_RENDERBUFFER 0x2003 +#define CL_GL_OBJECT_TEXTURE2D_ARRAY 0x200E +#define CL_GL_OBJECT_TEXTURE1D 0x200F +#define CL_GL_OBJECT_TEXTURE1D_ARRAY 0x2010 +#define CL_GL_OBJECT_TEXTURE_BUFFER 0x2011 + +/* cl_gl_texture_info */ +#define CL_GL_TEXTURE_TARGET 0x2004 +#define CL_GL_MIPMAP_LEVEL 0x2005 +#define CL_GL_NUM_SAMPLES 0x2012 + + +extern CL_API_ENTRY cl_mem CL_API_CALL +clCreateFromGLBuffer(cl_context /* context */, + cl_mem_flags /* flags */, + cl_GLuint /* bufobj */, + int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_mem CL_API_CALL +clCreateFromGLTexture(cl_context /* context */, + cl_mem_flags /* flags */, + cl_GLenum /* target */, + cl_GLint /* miplevel */, + cl_GLuint /* texture */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_2; + +extern CL_API_ENTRY cl_mem CL_API_CALL +clCreateFromGLRenderbuffer(cl_context /* context */, + cl_mem_flags /* flags */, + cl_GLuint /* renderbuffer */, + cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetGLObjectInfo(cl_mem /* memobj */, + cl_gl_object_type * /* gl_object_type */, + cl_GLuint * /* gl_object_name */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetGLTextureInfo(cl_mem /* memobj */, + cl_gl_texture_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueAcquireGLObjects(cl_command_queue /* command_queue */, + cl_uint /* num_objects */, + const cl_mem * /* mem_objects */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + +extern CL_API_ENTRY cl_int CL_API_CALL +clEnqueueReleaseGLObjects(cl_command_queue /* command_queue */, + cl_uint /* num_objects */, + const cl_mem * /* mem_objects */, + cl_uint /* num_events_in_wait_list */, + const cl_event * /* event_wait_list */, + cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0; + + +/* Deprecated OpenCL 1.1 APIs */ +extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL +clCreateFromGLTexture2D(cl_context /* context */, + cl_mem_flags /* flags */, + cl_GLenum /* target */, + cl_GLint /* miplevel */, + cl_GLuint /* texture */, + cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; + +extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL +clCreateFromGLTexture3D(cl_context /* context */, + cl_mem_flags /* flags */, + cl_GLenum /* target */, + cl_GLint /* miplevel */, + cl_GLuint /* texture */, + cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED; + +/* cl_khr_gl_sharing extension */ + +#define cl_khr_gl_sharing 1 + +typedef cl_uint cl_gl_context_info; + +/* Additional Error Codes */ +#define CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR -1000 + +/* cl_gl_context_info */ +#define CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR 0x2006 +#define CL_DEVICES_FOR_GL_CONTEXT_KHR 0x2007 + +/* Additional cl_context_properties */ +#define CL_GL_CONTEXT_KHR 0x2008 +#define CL_EGL_DISPLAY_KHR 0x2009 +#define CL_GLX_DISPLAY_KHR 0x200A +#define CL_WGL_HDC_KHR 0x200B +#define CL_CGL_SHAREGROUP_KHR 0x200C + +extern CL_API_ENTRY cl_int CL_API_CALL +clGetGLContextInfoKHR(const cl_context_properties * /* properties */, + cl_gl_context_info /* param_name */, + size_t /* param_value_size */, + void * /* param_value */, + size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0; + +typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetGLContextInfoKHR_fn)( + const cl_context_properties * properties, + cl_gl_context_info param_name, + size_t param_value_size, + void * param_value, + size_t * param_value_size_ret); + +#ifdef __cplusplus +} +#endif + +#endif /* __OPENCL_CL_GL_H */ diff --git a/include/lib/CL/cl_gl_ext.h b/include/lib/CL/cl_gl_ext.h new file mode 100644 index 0000000..0b2fc93 --- /dev/null +++ b/include/lib/CL/cl_gl_ext.h @@ -0,0 +1,69 @@ +/********************************************************************************** + * Copyright (c) 2008-2012 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + **********************************************************************************/ + +/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ + +/* cl_gl_ext.h contains vendor (non-KHR) OpenCL extensions which have */ +/* OpenGL dependencies. */ + +#ifndef __OPENCL_CL_GL_EXT_H +#define __OPENCL_CL_GL_EXT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __APPLE__ + #include +#else + #include +#endif + +/* + * For each extension, follow this template + * cl_VEN_extname extension */ +/* #define cl_VEN_extname 1 + * ... define new types, if any + * ... define new tokens, if any + * ... define new APIs, if any + * + * If you need GLtypes here, mirror them with a cl_GLtype, rather than including a GL header + * This allows us to avoid having to decide whether to include GL headers or GLES here. + */ + +/* + * cl_khr_gl_event extension + * See section 9.9 in the OpenCL 1.1 spec for more information + */ +#define CL_COMMAND_GL_FENCE_SYNC_OBJECT_KHR 0x200D + +extern CL_API_ENTRY cl_event CL_API_CALL +clCreateEventFromGLsyncKHR(cl_context /* context */, + cl_GLsync /* cl_GLsync */, + cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1; + +#ifdef __cplusplus +} +#endif + +#endif /* __OPENCL_CL_GL_EXT_H */ diff --git a/include/lib/CL/cl_platform.h b/include/lib/CL/cl_platform.h new file mode 100644 index 0000000..a583a54 --- /dev/null +++ b/include/lib/CL/cl_platform.h @@ -0,0 +1,1278 @@ +/********************************************************************************** + * Copyright (c) 2008-2012 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + **********************************************************************************/ + +/* $Revision: 11803 $ on $Date: 2010-06-25 10:02:12 -0700 (Fri, 25 Jun 2010) $ */ + +#ifndef __CL_PLATFORM_H +#define __CL_PLATFORM_H + +#ifdef __APPLE__ + /* Contains #defines for AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER below */ + #include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(_WIN32) + #define CL_API_ENTRY + #define CL_API_CALL __stdcall + #define CL_CALLBACK __stdcall +#else + #define CL_API_ENTRY + #define CL_API_CALL + #define CL_CALLBACK +#endif + +#ifdef __APPLE__ + #define CL_EXTENSION_WEAK_LINK __attribute__((weak_import)) + #define CL_API_SUFFIX__VERSION_1_0 AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER + #define CL_EXT_SUFFIX__VERSION_1_0 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER + #define CL_API_SUFFIX__VERSION_1_1 AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER + #define GCL_API_SUFFIX__VERSION_1_1 AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER + #define CL_EXT_SUFFIX__VERSION_1_1 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER + #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_7 + + #ifdef AVAILABLE_MAC_OS_X_VERSION_10_8_AND_LATER + #define CL_API_SUFFIX__VERSION_1_2 AVAILABLE_MAC_OS_X_VERSION_10_8_AND_LATER + #define GCL_API_SUFFIX__VERSION_1_2 AVAILABLE_MAC_OS_X_VERSION_10_8_AND_LATER + #define CL_EXT_SUFFIX__VERSION_1_2 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_8_AND_LATER + #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED + #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_8 + #else + #warning This path should never happen outside of internal operating system development. AvailabilityMacros do not function correctly here! + #define CL_API_SUFFIX__VERSION_1_2 AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER + #define GCL_API_SUFFIX__VERSION_1_2 AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER + #define CL_EXT_SUFFIX__VERSION_1_2 CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER + #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED CL_EXTENSION_WEAK_LINK AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER + #endif +#else + #define CL_EXTENSION_WEAK_LINK + #define CL_API_SUFFIX__VERSION_1_0 + #define CL_EXT_SUFFIX__VERSION_1_0 + #define CL_API_SUFFIX__VERSION_1_1 + #define CL_EXT_SUFFIX__VERSION_1_1 + #define CL_API_SUFFIX__VERSION_1_2 + #define CL_EXT_SUFFIX__VERSION_1_2 + + #ifdef __GNUC__ + #ifdef CL_USE_DEPRECATED_OPENCL_1_0_APIS + #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED + #define CL_EXT_PREFIX__VERSION_1_0_DEPRECATED + #else + #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED __attribute__((deprecated)) + #define CL_EXT_PREFIX__VERSION_1_0_DEPRECATED + #endif + + #ifdef CL_USE_DEPRECATED_OPENCL_1_1_APIS + #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED + #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED + #else + #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED __attribute__((deprecated)) + #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED + #endif + #elif _WIN32 + #ifdef CL_USE_DEPRECATED_OPENCL_1_0_APIS + #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED + #define CL_EXT_PREFIX__VERSION_1_0_DEPRECATED + #else + #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED + #define CL_EXT_PREFIX__VERSION_1_0_DEPRECATED __declspec(deprecated) + #endif + + #ifdef CL_USE_DEPRECATED_OPENCL_1_1_APIS + #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED + #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED + #else + #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED + #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED __declspec(deprecated) + #endif + #else + #define CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED + #define CL_EXT_PREFIX__VERSION_1_0_DEPRECATED + + #define CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED + #define CL_EXT_PREFIX__VERSION_1_1_DEPRECATED + #endif +#endif + +#if (defined (_WIN32) && defined(_MSC_VER)) + +/* scalar types */ +typedef signed __int8 cl_char; +typedef unsigned __int8 cl_uchar; +typedef signed __int16 cl_short; +typedef unsigned __int16 cl_ushort; +typedef signed __int32 cl_int; +typedef unsigned __int32 cl_uint; +typedef signed __int64 cl_long; +typedef unsigned __int64 cl_ulong; + +typedef unsigned __int16 cl_half; +typedef float cl_float; +typedef double cl_double; + +/* Macro names and corresponding values defined by OpenCL */ +#define CL_CHAR_BIT 8 +#define CL_SCHAR_MAX 127 +#define CL_SCHAR_MIN (-127-1) +#define CL_CHAR_MAX CL_SCHAR_MAX +#define CL_CHAR_MIN CL_SCHAR_MIN +#define CL_UCHAR_MAX 255 +#define CL_SHRT_MAX 32767 +#define CL_SHRT_MIN (-32767-1) +#define CL_USHRT_MAX 65535 +#define CL_INT_MAX 2147483647 +#define CL_INT_MIN (-2147483647-1) +#define CL_UINT_MAX 0xffffffffU +#define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) +#define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) +#define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) + +#define CL_FLT_DIG 6 +#define CL_FLT_MANT_DIG 24 +#define CL_FLT_MAX_10_EXP +38 +#define CL_FLT_MAX_EXP +128 +#define CL_FLT_MIN_10_EXP -37 +#define CL_FLT_MIN_EXP -125 +#define CL_FLT_RADIX 2 +#define CL_FLT_MAX 340282346638528859811704183484516925440.0f +#define CL_FLT_MIN 1.175494350822287507969e-38f +#define CL_FLT_EPSILON 0x1.0p-23f + +#define CL_DBL_DIG 15 +#define CL_DBL_MANT_DIG 53 +#define CL_DBL_MAX_10_EXP +308 +#define CL_DBL_MAX_EXP +1024 +#define CL_DBL_MIN_10_EXP -307 +#define CL_DBL_MIN_EXP -1021 +#define CL_DBL_RADIX 2 +#define CL_DBL_MAX 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0 +#define CL_DBL_MIN 2.225073858507201383090e-308 +#define CL_DBL_EPSILON 2.220446049250313080847e-16 + +#define CL_M_E 2.718281828459045090796 +#define CL_M_LOG2E 1.442695040888963387005 +#define CL_M_LOG10E 0.434294481903251816668 +#define CL_M_LN2 0.693147180559945286227 +#define CL_M_LN10 2.302585092994045901094 +#define CL_M_PI 3.141592653589793115998 +#define CL_M_PI_2 1.570796326794896557999 +#define CL_M_PI_4 0.785398163397448278999 +#define CL_M_1_PI 0.318309886183790691216 +#define CL_M_2_PI 0.636619772367581382433 +#define CL_M_2_SQRTPI 1.128379167095512558561 +#define CL_M_SQRT2 1.414213562373095145475 +#define CL_M_SQRT1_2 0.707106781186547572737 + +#define CL_M_E_F 2.71828174591064f +#define CL_M_LOG2E_F 1.44269502162933f +#define CL_M_LOG10E_F 0.43429449200630f +#define CL_M_LN2_F 0.69314718246460f +#define CL_M_LN10_F 2.30258512496948f +#define CL_M_PI_F 3.14159274101257f +#define CL_M_PI_2_F 1.57079637050629f +#define CL_M_PI_4_F 0.78539818525314f +#define CL_M_1_PI_F 0.31830987334251f +#define CL_M_2_PI_F 0.63661974668503f +#define CL_M_2_SQRTPI_F 1.12837922573090f +#define CL_M_SQRT2_F 1.41421353816986f +#define CL_M_SQRT1_2_F 0.70710676908493f + +#define CL_NAN (CL_INFINITY - CL_INFINITY) +#define CL_HUGE_VALF ((cl_float) 1e50) +#define CL_HUGE_VAL ((cl_double) 1e500) +#define CL_MAXFLOAT CL_FLT_MAX +#define CL_INFINITY CL_HUGE_VALF + +#else + +#include + +/* scalar types */ +typedef int8_t cl_char; +typedef uint8_t cl_uchar; +typedef int16_t cl_short __attribute__((aligned(2))); +typedef uint16_t cl_ushort __attribute__((aligned(2))); +typedef int32_t cl_int __attribute__((aligned(4))); +typedef uint32_t cl_uint __attribute__((aligned(4))); +typedef int64_t cl_long __attribute__((aligned(8))); +typedef uint64_t cl_ulong __attribute__((aligned(8))); + +typedef uint16_t cl_half __attribute__((aligned(2))); +typedef float cl_float __attribute__((aligned(4))); +typedef double cl_double __attribute__((aligned(8))); + +/* Macro names and corresponding values defined by OpenCL */ +#define CL_CHAR_BIT 8 +#define CL_SCHAR_MAX 127 +#define CL_SCHAR_MIN (-127-1) +#define CL_CHAR_MAX CL_SCHAR_MAX +#define CL_CHAR_MIN CL_SCHAR_MIN +#define CL_UCHAR_MAX 255 +#define CL_SHRT_MAX 32767 +#define CL_SHRT_MIN (-32767-1) +#define CL_USHRT_MAX 65535 +#define CL_INT_MAX 2147483647 +#define CL_INT_MIN (-2147483647-1) +#define CL_UINT_MAX 0xffffffffU +#define CL_LONG_MAX ((cl_long) 0x7FFFFFFFFFFFFFFFLL) +#define CL_LONG_MIN ((cl_long) -0x7FFFFFFFFFFFFFFFLL - 1LL) +#define CL_ULONG_MAX ((cl_ulong) 0xFFFFFFFFFFFFFFFFULL) + +#define CL_FLT_DIG 6 +#define CL_FLT_MANT_DIG 24 +#define CL_FLT_MAX_10_EXP +38 +#define CL_FLT_MAX_EXP +128 +#define CL_FLT_MIN_10_EXP -37 +#define CL_FLT_MIN_EXP -125 +#define CL_FLT_RADIX 2 +#define CL_FLT_MAX 0x1.fffffep127f +#define CL_FLT_MIN 0x1.0p-126f +#define CL_FLT_EPSILON 0x1.0p-23f + +#define CL_DBL_DIG 15 +#define CL_DBL_MANT_DIG 53 +#define CL_DBL_MAX_10_EXP +308 +#define CL_DBL_MAX_EXP +1024 +#define CL_DBL_MIN_10_EXP -307 +#define CL_DBL_MIN_EXP -1021 +#define CL_DBL_RADIX 2 +#define CL_DBL_MAX 0x1.fffffffffffffp1023 +#define CL_DBL_MIN 0x1.0p-1022 +#define CL_DBL_EPSILON 0x1.0p-52 + +#define CL_M_E 2.718281828459045090796 +#define CL_M_LOG2E 1.442695040888963387005 +#define CL_M_LOG10E 0.434294481903251816668 +#define CL_M_LN2 0.693147180559945286227 +#define CL_M_LN10 2.302585092994045901094 +#define CL_M_PI 3.141592653589793115998 +#define CL_M_PI_2 1.570796326794896557999 +#define CL_M_PI_4 0.785398163397448278999 +#define CL_M_1_PI 0.318309886183790691216 +#define CL_M_2_PI 0.636619772367581382433 +#define CL_M_2_SQRTPI 1.128379167095512558561 +#define CL_M_SQRT2 1.414213562373095145475 +#define CL_M_SQRT1_2 0.707106781186547572737 + +#define CL_M_E_F 2.71828174591064f +#define CL_M_LOG2E_F 1.44269502162933f +#define CL_M_LOG10E_F 0.43429449200630f +#define CL_M_LN2_F 0.69314718246460f +#define CL_M_LN10_F 2.30258512496948f +#define CL_M_PI_F 3.14159274101257f +#define CL_M_PI_2_F 1.57079637050629f +#define CL_M_PI_4_F 0.78539818525314f +#define CL_M_1_PI_F 0.31830987334251f +#define CL_M_2_PI_F 0.63661974668503f +#define CL_M_2_SQRTPI_F 1.12837922573090f +#define CL_M_SQRT2_F 1.41421353816986f +#define CL_M_SQRT1_2_F 0.70710676908493f + +#if defined( __GNUC__ ) + #define CL_HUGE_VALF __builtin_huge_valf() + #define CL_HUGE_VAL __builtin_huge_val() + #define CL_NAN __builtin_nanf( "" ) +#else + #define CL_HUGE_VALF ((cl_float) 1e50) + #define CL_HUGE_VAL ((cl_double) 1e500) + float nanf( const char * ); + #define CL_NAN nanf( "" ) +#endif +#define CL_MAXFLOAT CL_FLT_MAX +#define CL_INFINITY CL_HUGE_VALF + +#endif + +#include + +/* Mirror types to GL types. Mirror types allow us to avoid deciding which 87s to load based on whether we are using GL or GLES here. */ +typedef unsigned int cl_GLuint; +typedef int cl_GLint; +typedef unsigned int cl_GLenum; + +/* + * Vector types + * + * Note: OpenCL requires that all types be naturally aligned. + * This means that vector types must be naturally aligned. + * For example, a vector of four floats must be aligned to + * a 16 byte boundary (calculated as 4 * the natural 4-byte + * alignment of the float). The alignment qualifiers here + * will only function properly if your compiler supports them + * and if you don't actively work to defeat them. For example, + * in order for a cl_float4 to be 16 byte aligned in a struct, + * the start of the struct must itself be 16-byte aligned. + * + * Maintaining proper alignment is the user's responsibility. + */ + +/* Define basic vector types */ +#if defined( __VEC__ ) + #include /* may be omitted depending on compiler. AltiVec spec provides no way to detect whether the header is required. */ + typedef vector unsigned char __cl_uchar16; + typedef vector signed char __cl_char16; + typedef vector unsigned short __cl_ushort8; + typedef vector signed short __cl_short8; + typedef vector unsigned int __cl_uint4; + typedef vector signed int __cl_int4; + typedef vector float __cl_float4; + #define __CL_UCHAR16__ 1 + #define __CL_CHAR16__ 1 + #define __CL_USHORT8__ 1 + #define __CL_SHORT8__ 1 + #define __CL_UINT4__ 1 + #define __CL_INT4__ 1 + #define __CL_FLOAT4__ 1 +#endif + +#if defined( __SSE__ ) + #if defined( __MINGW64__ ) + #include + #else + #include + #endif + #if defined( __GNUC__ ) + typedef float __cl_float4 __attribute__((vector_size(16))); + #else + typedef __m128 __cl_float4; + #endif + #define __CL_FLOAT4__ 1 +#endif + +#if defined( __SSE2__ ) + #if defined( __MINGW64__ ) + #include + #else + #include + #endif + #if defined( __GNUC__ ) + typedef cl_uchar __cl_uchar16 __attribute__((vector_size(16))); + typedef cl_char __cl_char16 __attribute__((vector_size(16))); + typedef cl_ushort __cl_ushort8 __attribute__((vector_size(16))); + typedef cl_short __cl_short8 __attribute__((vector_size(16))); + typedef cl_uint __cl_uint4 __attribute__((vector_size(16))); + typedef cl_int __cl_int4 __attribute__((vector_size(16))); + typedef cl_ulong __cl_ulong2 __attribute__((vector_size(16))); + typedef cl_long __cl_long2 __attribute__((vector_size(16))); + typedef cl_double __cl_double2 __attribute__((vector_size(16))); + #else + typedef __m128i __cl_uchar16; + typedef __m128i __cl_char16; + typedef __m128i __cl_ushort8; + typedef __m128i __cl_short8; + typedef __m128i __cl_uint4; + typedef __m128i __cl_int4; + typedef __m128i __cl_ulong2; + typedef __m128i __cl_long2; + typedef __m128d __cl_double2; + #endif + #define __CL_UCHAR16__ 1 + #define __CL_CHAR16__ 1 + #define __CL_USHORT8__ 1 + #define __CL_SHORT8__ 1 + #define __CL_INT4__ 1 + #define __CL_UINT4__ 1 + #define __CL_ULONG2__ 1 + #define __CL_LONG2__ 1 + #define __CL_DOUBLE2__ 1 +#endif + +#if defined( __MMX__ ) + #include + #if defined( __GNUC__ ) + typedef cl_uchar __cl_uchar8 __attribute__((vector_size(8))); + typedef cl_char __cl_char8 __attribute__((vector_size(8))); + typedef cl_ushort __cl_ushort4 __attribute__((vector_size(8))); + typedef cl_short __cl_short4 __attribute__((vector_size(8))); + typedef cl_uint __cl_uint2 __attribute__((vector_size(8))); + typedef cl_int __cl_int2 __attribute__((vector_size(8))); + typedef cl_ulong __cl_ulong1 __attribute__((vector_size(8))); + typedef cl_long __cl_long1 __attribute__((vector_size(8))); + typedef cl_float __cl_float2 __attribute__((vector_size(8))); + #else + typedef __m64 __cl_uchar8; + typedef __m64 __cl_char8; + typedef __m64 __cl_ushort4; + typedef __m64 __cl_short4; + typedef __m64 __cl_uint2; + typedef __m64 __cl_int2; + typedef __m64 __cl_ulong1; + typedef __m64 __cl_long1; + typedef __m64 __cl_float2; + #endif + #define __CL_UCHAR8__ 1 + #define __CL_CHAR8__ 1 + #define __CL_USHORT4__ 1 + #define __CL_SHORT4__ 1 + #define __CL_INT2__ 1 + #define __CL_UINT2__ 1 + #define __CL_ULONG1__ 1 + #define __CL_LONG1__ 1 + #define __CL_FLOAT2__ 1 +#endif + +#if defined( __AVX__ ) + #if defined( __MINGW64__ ) + #include + #else + #include + #endif + #if defined( __GNUC__ ) + typedef cl_float __cl_float8 __attribute__((vector_size(32))); + typedef cl_double __cl_double4 __attribute__((vector_size(32))); + #else + typedef __m256 __cl_float8; + typedef __m256d __cl_double4; + #endif + #define __CL_FLOAT8__ 1 + #define __CL_DOUBLE4__ 1 +#endif + +/* Define capabilities for anonymous struct members. */ +#if defined( __GNUC__) && ! defined( __STRICT_ANSI__ ) +#define __CL_HAS_ANON_STRUCT__ 1 +#define __CL_ANON_STRUCT__ __extension__ +#elif defined( _WIN32) && (_MSC_VER >= 1500) + /* Microsoft Developer Studio 2008 supports anonymous structs, but + * complains by default. */ +#define __CL_HAS_ANON_STRUCT__ 1 +#define __CL_ANON_STRUCT__ + /* Disable warning C4201: nonstandard extension used : nameless + * struct/union */ +#pragma warning( push ) +#pragma warning( disable : 4201 ) +#else +#define __CL_HAS_ANON_STRUCT__ 0 +#define __CL_ANON_STRUCT__ +#endif + +/* Define alignment keys */ +#if defined( __GNUC__ ) + #define CL_ALIGNED(_x) __attribute__ ((aligned(_x))) +#elif defined( _WIN32) && (_MSC_VER) + /* Alignment keys neutered on windows because MSVC can't swallow function arguments with alignment requirements */ + /* http://msdn.microsoft.com/en-us/library/373ak2y1%28VS.71%29.aspx */ + /* #include */ + /* #define CL_ALIGNED(_x) _CRT_ALIGN(_x) */ + #define CL_ALIGNED(_x) +#else + #warning Need to implement some method to align data here + #define CL_ALIGNED(_x) +#endif + +/* Indicate whether .xyzw, .s0123 and .hi.lo are supported */ +#if __CL_HAS_ANON_STRUCT__ + /* .xyzw and .s0123...{f|F} are supported */ + #define CL_HAS_NAMED_VECTOR_FIELDS 1 + /* .hi and .lo are supported */ + #define CL_HAS_HI_LO_VECTOR_FIELDS 1 +#endif + +/* Define cl_vector types */ + +/* ---- cl_charn ---- */ +typedef union +{ + cl_char CL_ALIGNED(2) s[2]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_char x, y; }; + __CL_ANON_STRUCT__ struct{ cl_char s0, s1; }; + __CL_ANON_STRUCT__ struct{ cl_char lo, hi; }; +#endif +#if defined( __CL_CHAR2__) + __cl_char2 v2; +#endif +}cl_char2; + +typedef union +{ + cl_char CL_ALIGNED(4) s[4]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_char x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_char s0, s1, s2, s3; }; + __CL_ANON_STRUCT__ struct{ cl_char2 lo, hi; }; +#endif +#if defined( __CL_CHAR2__) + __cl_char2 v2[2]; +#endif +#if defined( __CL_CHAR4__) + __cl_char4 v4; +#endif +}cl_char4; + +/* cl_char3 is identical in size, alignment and behavior to cl_char4. See section 6.1.5. */ +typedef cl_char4 cl_char3; + +typedef union +{ + cl_char CL_ALIGNED(8) s[8]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_char x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_char s0, s1, s2, s3, s4, s5, s6, s7; }; + __CL_ANON_STRUCT__ struct{ cl_char4 lo, hi; }; +#endif +#if defined( __CL_CHAR2__) + __cl_char2 v2[4]; +#endif +#if defined( __CL_CHAR4__) + __cl_char4 v4[2]; +#endif +#if defined( __CL_CHAR8__ ) + __cl_char8 v8; +#endif +}cl_char8; + +typedef union +{ + cl_char CL_ALIGNED(16) s[16]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_char x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; + __CL_ANON_STRUCT__ struct{ cl_char s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; + __CL_ANON_STRUCT__ struct{ cl_char8 lo, hi; }; +#endif +#if defined( __CL_CHAR2__) + __cl_char2 v2[8]; +#endif +#if defined( __CL_CHAR4__) + __cl_char4 v4[4]; +#endif +#if defined( __CL_CHAR8__ ) + __cl_char8 v8[2]; +#endif +#if defined( __CL_CHAR16__ ) + __cl_char16 v16; +#endif +}cl_char16; + + +/* ---- cl_ucharn ---- */ +typedef union +{ + cl_uchar CL_ALIGNED(2) s[2]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_uchar x, y; }; + __CL_ANON_STRUCT__ struct{ cl_uchar s0, s1; }; + __CL_ANON_STRUCT__ struct{ cl_uchar lo, hi; }; +#endif +#if defined( __cl_uchar2__) + __cl_uchar2 v2; +#endif +}cl_uchar2; + +typedef union +{ + cl_uchar CL_ALIGNED(4) s[4]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_uchar x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_uchar s0, s1, s2, s3; }; + __CL_ANON_STRUCT__ struct{ cl_uchar2 lo, hi; }; +#endif +#if defined( __CL_UCHAR2__) + __cl_uchar2 v2[2]; +#endif +#if defined( __CL_UCHAR4__) + __cl_uchar4 v4; +#endif +}cl_uchar4; + +/* cl_uchar3 is identical in size, alignment and behavior to cl_uchar4. See section 6.1.5. */ +typedef cl_uchar4 cl_uchar3; + +typedef union +{ + cl_uchar CL_ALIGNED(8) s[8]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_uchar x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_uchar s0, s1, s2, s3, s4, s5, s6, s7; }; + __CL_ANON_STRUCT__ struct{ cl_uchar4 lo, hi; }; +#endif +#if defined( __CL_UCHAR2__) + __cl_uchar2 v2[4]; +#endif +#if defined( __CL_UCHAR4__) + __cl_uchar4 v4[2]; +#endif +#if defined( __CL_UCHAR8__ ) + __cl_uchar8 v8; +#endif +}cl_uchar8; + +typedef union +{ + cl_uchar CL_ALIGNED(16) s[16]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_uchar x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; + __CL_ANON_STRUCT__ struct{ cl_uchar s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; + __CL_ANON_STRUCT__ struct{ cl_uchar8 lo, hi; }; +#endif +#if defined( __CL_UCHAR2__) + __cl_uchar2 v2[8]; +#endif +#if defined( __CL_UCHAR4__) + __cl_uchar4 v4[4]; +#endif +#if defined( __CL_UCHAR8__ ) + __cl_uchar8 v8[2]; +#endif +#if defined( __CL_UCHAR16__ ) + __cl_uchar16 v16; +#endif +}cl_uchar16; + + +/* ---- cl_shortn ---- */ +typedef union +{ + cl_short CL_ALIGNED(4) s[2]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_short x, y; }; + __CL_ANON_STRUCT__ struct{ cl_short s0, s1; }; + __CL_ANON_STRUCT__ struct{ cl_short lo, hi; }; +#endif +#if defined( __CL_SHORT2__) + __cl_short2 v2; +#endif +}cl_short2; + +typedef union +{ + cl_short CL_ALIGNED(8) s[4]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_short x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_short s0, s1, s2, s3; }; + __CL_ANON_STRUCT__ struct{ cl_short2 lo, hi; }; +#endif +#if defined( __CL_SHORT2__) + __cl_short2 v2[2]; +#endif +#if defined( __CL_SHORT4__) + __cl_short4 v4; +#endif +}cl_short4; + +/* cl_short3 is identical in size, alignment and behavior to cl_short4. See section 6.1.5. */ +typedef cl_short4 cl_short3; + +typedef union +{ + cl_short CL_ALIGNED(16) s[8]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_short x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_short s0, s1, s2, s3, s4, s5, s6, s7; }; + __CL_ANON_STRUCT__ struct{ cl_short4 lo, hi; }; +#endif +#if defined( __CL_SHORT2__) + __cl_short2 v2[4]; +#endif +#if defined( __CL_SHORT4__) + __cl_short4 v4[2]; +#endif +#if defined( __CL_SHORT8__ ) + __cl_short8 v8; +#endif +}cl_short8; + +typedef union +{ + cl_short CL_ALIGNED(32) s[16]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_short x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; + __CL_ANON_STRUCT__ struct{ cl_short s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; + __CL_ANON_STRUCT__ struct{ cl_short8 lo, hi; }; +#endif +#if defined( __CL_SHORT2__) + __cl_short2 v2[8]; +#endif +#if defined( __CL_SHORT4__) + __cl_short4 v4[4]; +#endif +#if defined( __CL_SHORT8__ ) + __cl_short8 v8[2]; +#endif +#if defined( __CL_SHORT16__ ) + __cl_short16 v16; +#endif +}cl_short16; + + +/* ---- cl_ushortn ---- */ +typedef union +{ + cl_ushort CL_ALIGNED(4) s[2]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_ushort x, y; }; + __CL_ANON_STRUCT__ struct{ cl_ushort s0, s1; }; + __CL_ANON_STRUCT__ struct{ cl_ushort lo, hi; }; +#endif +#if defined( __CL_USHORT2__) + __cl_ushort2 v2; +#endif +}cl_ushort2; + +typedef union +{ + cl_ushort CL_ALIGNED(8) s[4]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_ushort x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_ushort s0, s1, s2, s3; }; + __CL_ANON_STRUCT__ struct{ cl_ushort2 lo, hi; }; +#endif +#if defined( __CL_USHORT2__) + __cl_ushort2 v2[2]; +#endif +#if defined( __CL_USHORT4__) + __cl_ushort4 v4; +#endif +}cl_ushort4; + +/* cl_ushort3 is identical in size, alignment and behavior to cl_ushort4. See section 6.1.5. */ +typedef cl_ushort4 cl_ushort3; + +typedef union +{ + cl_ushort CL_ALIGNED(16) s[8]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_ushort x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_ushort s0, s1, s2, s3, s4, s5, s6, s7; }; + __CL_ANON_STRUCT__ struct{ cl_ushort4 lo, hi; }; +#endif +#if defined( __CL_USHORT2__) + __cl_ushort2 v2[4]; +#endif +#if defined( __CL_USHORT4__) + __cl_ushort4 v4[2]; +#endif +#if defined( __CL_USHORT8__ ) + __cl_ushort8 v8; +#endif +}cl_ushort8; + +typedef union +{ + cl_ushort CL_ALIGNED(32) s[16]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_ushort x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; + __CL_ANON_STRUCT__ struct{ cl_ushort s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; + __CL_ANON_STRUCT__ struct{ cl_ushort8 lo, hi; }; +#endif +#if defined( __CL_USHORT2__) + __cl_ushort2 v2[8]; +#endif +#if defined( __CL_USHORT4__) + __cl_ushort4 v4[4]; +#endif +#if defined( __CL_USHORT8__ ) + __cl_ushort8 v8[2]; +#endif +#if defined( __CL_USHORT16__ ) + __cl_ushort16 v16; +#endif +}cl_ushort16; + +/* ---- cl_intn ---- */ +typedef union +{ + cl_int CL_ALIGNED(8) s[2]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_int x, y; }; + __CL_ANON_STRUCT__ struct{ cl_int s0, s1; }; + __CL_ANON_STRUCT__ struct{ cl_int lo, hi; }; +#endif +#if defined( __CL_INT2__) + __cl_int2 v2; +#endif +}cl_int2; + +typedef union +{ + cl_int CL_ALIGNED(16) s[4]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_int x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_int s0, s1, s2, s3; }; + __CL_ANON_STRUCT__ struct{ cl_int2 lo, hi; }; +#endif +#if defined( __CL_INT2__) + __cl_int2 v2[2]; +#endif +#if defined( __CL_INT4__) + __cl_int4 v4; +#endif +}cl_int4; + +/* cl_int3 is identical in size, alignment and behavior to cl_int4. See section 6.1.5. */ +typedef cl_int4 cl_int3; + +typedef union +{ + cl_int CL_ALIGNED(32) s[8]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_int x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_int s0, s1, s2, s3, s4, s5, s6, s7; }; + __CL_ANON_STRUCT__ struct{ cl_int4 lo, hi; }; +#endif +#if defined( __CL_INT2__) + __cl_int2 v2[4]; +#endif +#if defined( __CL_INT4__) + __cl_int4 v4[2]; +#endif +#if defined( __CL_INT8__ ) + __cl_int8 v8; +#endif +}cl_int8; + +typedef union +{ + cl_int CL_ALIGNED(64) s[16]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_int x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; + __CL_ANON_STRUCT__ struct{ cl_int s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; + __CL_ANON_STRUCT__ struct{ cl_int8 lo, hi; }; +#endif +#if defined( __CL_INT2__) + __cl_int2 v2[8]; +#endif +#if defined( __CL_INT4__) + __cl_int4 v4[4]; +#endif +#if defined( __CL_INT8__ ) + __cl_int8 v8[2]; +#endif +#if defined( __CL_INT16__ ) + __cl_int16 v16; +#endif +}cl_int16; + + +/* ---- cl_uintn ---- */ +typedef union +{ + cl_uint CL_ALIGNED(8) s[2]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_uint x, y; }; + __CL_ANON_STRUCT__ struct{ cl_uint s0, s1; }; + __CL_ANON_STRUCT__ struct{ cl_uint lo, hi; }; +#endif +#if defined( __CL_UINT2__) + __cl_uint2 v2; +#endif +}cl_uint2; + +typedef union +{ + cl_uint CL_ALIGNED(16) s[4]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_uint x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_uint s0, s1, s2, s3; }; + __CL_ANON_STRUCT__ struct{ cl_uint2 lo, hi; }; +#endif +#if defined( __CL_UINT2__) + __cl_uint2 v2[2]; +#endif +#if defined( __CL_UINT4__) + __cl_uint4 v4; +#endif +}cl_uint4; + +/* cl_uint3 is identical in size, alignment and behavior to cl_uint4. See section 6.1.5. */ +typedef cl_uint4 cl_uint3; + +typedef union +{ + cl_uint CL_ALIGNED(32) s[8]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_uint x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_uint s0, s1, s2, s3, s4, s5, s6, s7; }; + __CL_ANON_STRUCT__ struct{ cl_uint4 lo, hi; }; +#endif +#if defined( __CL_UINT2__) + __cl_uint2 v2[4]; +#endif +#if defined( __CL_UINT4__) + __cl_uint4 v4[2]; +#endif +#if defined( __CL_UINT8__ ) + __cl_uint8 v8; +#endif +}cl_uint8; + +typedef union +{ + cl_uint CL_ALIGNED(64) s[16]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_uint x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; + __CL_ANON_STRUCT__ struct{ cl_uint s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; + __CL_ANON_STRUCT__ struct{ cl_uint8 lo, hi; }; +#endif +#if defined( __CL_UINT2__) + __cl_uint2 v2[8]; +#endif +#if defined( __CL_UINT4__) + __cl_uint4 v4[4]; +#endif +#if defined( __CL_UINT8__ ) + __cl_uint8 v8[2]; +#endif +#if defined( __CL_UINT16__ ) + __cl_uint16 v16; +#endif +}cl_uint16; + +/* ---- cl_longn ---- */ +typedef union +{ + cl_long CL_ALIGNED(16) s[2]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_long x, y; }; + __CL_ANON_STRUCT__ struct{ cl_long s0, s1; }; + __CL_ANON_STRUCT__ struct{ cl_long lo, hi; }; +#endif +#if defined( __CL_LONG2__) + __cl_long2 v2; +#endif +}cl_long2; + +typedef union +{ + cl_long CL_ALIGNED(32) s[4]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_long x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_long s0, s1, s2, s3; }; + __CL_ANON_STRUCT__ struct{ cl_long2 lo, hi; }; +#endif +#if defined( __CL_LONG2__) + __cl_long2 v2[2]; +#endif +#if defined( __CL_LONG4__) + __cl_long4 v4; +#endif +}cl_long4; + +/* cl_long3 is identical in size, alignment and behavior to cl_long4. See section 6.1.5. */ +typedef cl_long4 cl_long3; + +typedef union +{ + cl_long CL_ALIGNED(64) s[8]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_long x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_long s0, s1, s2, s3, s4, s5, s6, s7; }; + __CL_ANON_STRUCT__ struct{ cl_long4 lo, hi; }; +#endif +#if defined( __CL_LONG2__) + __cl_long2 v2[4]; +#endif +#if defined( __CL_LONG4__) + __cl_long4 v4[2]; +#endif +#if defined( __CL_LONG8__ ) + __cl_long8 v8; +#endif +}cl_long8; + +typedef union +{ + cl_long CL_ALIGNED(128) s[16]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_long x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; + __CL_ANON_STRUCT__ struct{ cl_long s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; + __CL_ANON_STRUCT__ struct{ cl_long8 lo, hi; }; +#endif +#if defined( __CL_LONG2__) + __cl_long2 v2[8]; +#endif +#if defined( __CL_LONG4__) + __cl_long4 v4[4]; +#endif +#if defined( __CL_LONG8__ ) + __cl_long8 v8[2]; +#endif +#if defined( __CL_LONG16__ ) + __cl_long16 v16; +#endif +}cl_long16; + + +/* ---- cl_ulongn ---- */ +typedef union +{ + cl_ulong CL_ALIGNED(16) s[2]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_ulong x, y; }; + __CL_ANON_STRUCT__ struct{ cl_ulong s0, s1; }; + __CL_ANON_STRUCT__ struct{ cl_ulong lo, hi; }; +#endif +#if defined( __CL_ULONG2__) + __cl_ulong2 v2; +#endif +}cl_ulong2; + +typedef union +{ + cl_ulong CL_ALIGNED(32) s[4]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_ulong x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_ulong s0, s1, s2, s3; }; + __CL_ANON_STRUCT__ struct{ cl_ulong2 lo, hi; }; +#endif +#if defined( __CL_ULONG2__) + __cl_ulong2 v2[2]; +#endif +#if defined( __CL_ULONG4__) + __cl_ulong4 v4; +#endif +}cl_ulong4; + +/* cl_ulong3 is identical in size, alignment and behavior to cl_ulong4. See section 6.1.5. */ +typedef cl_ulong4 cl_ulong3; + +typedef union +{ + cl_ulong CL_ALIGNED(64) s[8]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_ulong x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_ulong s0, s1, s2, s3, s4, s5, s6, s7; }; + __CL_ANON_STRUCT__ struct{ cl_ulong4 lo, hi; }; +#endif +#if defined( __CL_ULONG2__) + __cl_ulong2 v2[4]; +#endif +#if defined( __CL_ULONG4__) + __cl_ulong4 v4[2]; +#endif +#if defined( __CL_ULONG8__ ) + __cl_ulong8 v8; +#endif +}cl_ulong8; + +typedef union +{ + cl_ulong CL_ALIGNED(128) s[16]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_ulong x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; + __CL_ANON_STRUCT__ struct{ cl_ulong s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; + __CL_ANON_STRUCT__ struct{ cl_ulong8 lo, hi; }; +#endif +#if defined( __CL_ULONG2__) + __cl_ulong2 v2[8]; +#endif +#if defined( __CL_ULONG4__) + __cl_ulong4 v4[4]; +#endif +#if defined( __CL_ULONG8__ ) + __cl_ulong8 v8[2]; +#endif +#if defined( __CL_ULONG16__ ) + __cl_ulong16 v16; +#endif +}cl_ulong16; + + +/* --- cl_floatn ---- */ + +typedef union +{ + cl_float CL_ALIGNED(8) s[2]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_float x, y; }; + __CL_ANON_STRUCT__ struct{ cl_float s0, s1; }; + __CL_ANON_STRUCT__ struct{ cl_float lo, hi; }; +#endif +#if defined( __CL_FLOAT2__) + __cl_float2 v2; +#endif +}cl_float2; + +typedef union +{ + cl_float CL_ALIGNED(16) s[4]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_float x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_float s0, s1, s2, s3; }; + __CL_ANON_STRUCT__ struct{ cl_float2 lo, hi; }; +#endif +#if defined( __CL_FLOAT2__) + __cl_float2 v2[2]; +#endif +#if defined( __CL_FLOAT4__) + __cl_float4 v4; +#endif +}cl_float4; + +/* cl_float3 is identical in size, alignment and behavior to cl_float4. See section 6.1.5. */ +typedef cl_float4 cl_float3; + +typedef union +{ + cl_float CL_ALIGNED(32) s[8]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_float x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_float s0, s1, s2, s3, s4, s5, s6, s7; }; + __CL_ANON_STRUCT__ struct{ cl_float4 lo, hi; }; +#endif +#if defined( __CL_FLOAT2__) + __cl_float2 v2[4]; +#endif +#if defined( __CL_FLOAT4__) + __cl_float4 v4[2]; +#endif +#if defined( __CL_FLOAT8__ ) + __cl_float8 v8; +#endif +}cl_float8; + +typedef union +{ + cl_float CL_ALIGNED(64) s[16]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_float x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; + __CL_ANON_STRUCT__ struct{ cl_float s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; + __CL_ANON_STRUCT__ struct{ cl_float8 lo, hi; }; +#endif +#if defined( __CL_FLOAT2__) + __cl_float2 v2[8]; +#endif +#if defined( __CL_FLOAT4__) + __cl_float4 v4[4]; +#endif +#if defined( __CL_FLOAT8__ ) + __cl_float8 v8[2]; +#endif +#if defined( __CL_FLOAT16__ ) + __cl_float16 v16; +#endif +}cl_float16; + +/* --- cl_doublen ---- */ + +typedef union +{ + cl_double CL_ALIGNED(16) s[2]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_double x, y; }; + __CL_ANON_STRUCT__ struct{ cl_double s0, s1; }; + __CL_ANON_STRUCT__ struct{ cl_double lo, hi; }; +#endif +#if defined( __CL_DOUBLE2__) + __cl_double2 v2; +#endif +}cl_double2; + +typedef union +{ + cl_double CL_ALIGNED(32) s[4]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_double x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_double s0, s1, s2, s3; }; + __CL_ANON_STRUCT__ struct{ cl_double2 lo, hi; }; +#endif +#if defined( __CL_DOUBLE2__) + __cl_double2 v2[2]; +#endif +#if defined( __CL_DOUBLE4__) + __cl_double4 v4; +#endif +}cl_double4; + +/* cl_double3 is identical in size, alignment and behavior to cl_double4. See section 6.1.5. */ +typedef cl_double4 cl_double3; + +typedef union +{ + cl_double CL_ALIGNED(64) s[8]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_double x, y, z, w; }; + __CL_ANON_STRUCT__ struct{ cl_double s0, s1, s2, s3, s4, s5, s6, s7; }; + __CL_ANON_STRUCT__ struct{ cl_double4 lo, hi; }; +#endif +#if defined( __CL_DOUBLE2__) + __cl_double2 v2[4]; +#endif +#if defined( __CL_DOUBLE4__) + __cl_double4 v4[2]; +#endif +#if defined( __CL_DOUBLE8__ ) + __cl_double8 v8; +#endif +}cl_double8; + +typedef union +{ + cl_double CL_ALIGNED(128) s[16]; +#if __CL_HAS_ANON_STRUCT__ + __CL_ANON_STRUCT__ struct{ cl_double x, y, z, w, __spacer4, __spacer5, __spacer6, __spacer7, __spacer8, __spacer9, sa, sb, sc, sd, se, sf; }; + __CL_ANON_STRUCT__ struct{ cl_double s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, sA, sB, sC, sD, sE, sF; }; + __CL_ANON_STRUCT__ struct{ cl_double8 lo, hi; }; +#endif +#if defined( __CL_DOUBLE2__) + __cl_double2 v2[8]; +#endif +#if defined( __CL_DOUBLE4__) + __cl_double4 v4[4]; +#endif +#if defined( __CL_DOUBLE8__ ) + __cl_double8 v8[2]; +#endif +#if defined( __CL_DOUBLE16__ ) + __cl_double16 v16; +#endif +}cl_double16; + +/* Macro to facilitate debugging + * Usage: + * Place CL_PROGRAM_STRING_DEBUG_INFO on the line before the first line of your source. + * The first line ends with: CL_PROGRAM_STRING_DEBUG_INFO \" + * Each line thereafter of OpenCL C source must end with: \n\ + * The last line ends in "; + * + * Example: + * + * const char *my_program = CL_PROGRAM_STRING_DEBUG_INFO "\ + * kernel void foo( int a, float * b ) \n\ + * { \n\ + * // my comment \n\ + * *b[ get_global_id(0)] = a; \n\ + * } \n\ + * "; + * + * This should correctly set up the line, (column) and file information for your source + * string so you can do source level debugging. + */ +#define __CL_STRINGIFY( _x ) # _x +#define _CL_STRINGIFY( _x ) __CL_STRINGIFY( _x ) +#define CL_PROGRAM_STRING_DEBUG_INFO "#line " _CL_STRINGIFY(__LINE__) " \"" __FILE__ "\" \n\n" + +#ifdef __cplusplus +} +#endif + +#undef __CL_HAS_ANON_STRUCT__ +#undef __CL_ANON_STRUCT__ +#if defined( _WIN32) && (_MSC_VER >= 1500) +#pragma warning( pop ) +#endif + +#endif /* __CL_PLATFORM_H */ diff --git a/include/lib/CL/opencl.h b/include/lib/CL/opencl.h new file mode 100644 index 0000000..31b16e9 --- /dev/null +++ b/include/lib/CL/opencl.h @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (c) 2008-2012 The Khronos Group Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and/or associated documentation files (the + * "Materials"), to deal in the Materials without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Materials, and to + * permit persons to whom the Materials are furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Materials. + * + * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + ******************************************************************************/ + +/* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */ + +#ifndef __OPENCL_H +#define __OPENCL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef __APPLE__ + +#include +#include +#include +#include + +#else + +#include +#include +#include +#include + +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* __OPENCL_H */ + diff --git a/include/model/backendImageProcessor/Bip.h b/include/model/backendImageProcessor/Bip.h new file mode 100644 index 0000000..0805386 --- /dev/null +++ b/include/model/backendImageProcessor/Bip.h @@ -0,0 +1,53 @@ +#ifndef BIP_H +#define BIP_H + +#include + +#include "model/ultrasoundModule/UsModule.h" +#include "model/backendImageProcessor/core/BipCore.h" +#include "model/scenarioGenerator/dto/software/SoftwareOutput.h" +#include "model/backendImageProcessor/dto/BipImage.h" +#include "model/databaseManager/type/EDatabaseRequest.h" +#include "model/backendImageProcessor/utils/KernelInputFetcher.h" +#include "model/backendImageProcessor/dtoInternal/BipInput.h" + +/*************************************************************************************************/ +/** + * @brief The class is responsible for processing frames with GPU's aid + * @author Mohsen Emami - revised by h-4nd-h + * @date 2019/8/5(1398/5/14) + */ +/*************************************************************************************************/ +class Bip : public UsModule +{ + Q_OBJECT + US_MODULE + SINGLETON(Bip) + +private: + BipCore* _core; + + KernelInputFetcher* _kernelInput; + + Bip(); + + void sendDataToEvocator(const UsPacket& packet); + void sendDataToViewModel(const BipImage_t& outputImage); + +public: + ~Bip() override + { + } + +signals: + void sendOutputImageToViewModel(QVariant outputImage); + +//uncrustify off +public slots: +//uncrustify on + void newOuput(const UsPacket& evocData, const BipImage_t& outputImage); + void requestDataFromDatabase(EDatabaseRequest::eDatabaseRequest request, + const QList args); +}; + +#endif //BIP_H diff --git a/include/model/backendImageProcessor/core/BaseStrategy.h b/include/model/backendImageProcessor/core/BaseStrategy.h new file mode 100644 index 0000000..37c7188 --- /dev/null +++ b/include/model/backendImageProcessor/core/BaseStrategy.h @@ -0,0 +1,52 @@ +#ifndef BASESTRATEGY_H +#define BASESTRATEGY_H + +#include + +#include "model/backendImageProcessor/utils/OpenClHelper.h" +#include "model/ultrasoundModule/metadata/UsMetadataBag.h" +#include "model/backendImageProcessor/dtoInternal/KernelInput.h" + +class BaseStrategy : public QObject +{ + Q_OBJECT + +private: + void saveOuput(cl::Image* inputFrame, UsMetadataBag& metadata); + +protected: + cl::Kernel _clKernel; + cl::Context _clContext; + cl::CommandQueue _clQueue; + OpenClHelper _openClHelper; + + cl::Device getDefaultDevice(const cl::Context& context); + + virtual cl::Image* gpuProcess(cl::Image* inputFrame, + UsMetadataBag& metadata, + cl::Buffer* scrathPad) = 0; + virtual void finalize() = 0; + +public: + BaseStrategy(const cl::Context context, + const cl::CommandQueue queue, + const QString kernelPath, + const QString kernelName); + + virtual void cpuProcess(KernelInput_t parameters) = 0; + +signals: + void gpuDataReady(cl::Image* frames, + UsMetadataBag& metadata, + cl::Buffer* scrathPad); + +//uncrustify off +public slots: +//uncrustify on + void newGpuData(cl::Image* frames, + UsMetadataBag& metadata, + cl::Buffer* scrathPad); + void newCpuData(KernelInput_t parameters); +}; + +#endif //BASESTRATEGY_H diff --git a/include/model/backendImageProcessor/core/BipCore.h b/include/model/backendImageProcessor/core/BipCore.h new file mode 100644 index 0000000..b874b53 --- /dev/null +++ b/include/model/backendImageProcessor/core/BipCore.h @@ -0,0 +1,90 @@ +#ifndef BIPCORE_H +#define BIPCORE_H + +#include + +#include "model/backendImageProcessor/core/process/ProcessQueue.h" +#include "model/backendImageProcessor/core/process/ProcessQueueFactory.h" +#include "model/backendImageProcessor/type/EImageMode.h" +#include "model/backendImageProcessor/dtoInternal/BipInput.h" +#include "model/backendImageProcessor/utils/OpenClHelper.h" +#include "config/Configuration.h" +#include "model/hardware/Hardware.h" +#include "model/backendImageProcessor/dto/BipImage.h" +#include "model/ultrasoundModule/metadata/HardwareMetadata.h" +#include "model/ultrasoundModule/metadata/BMetadata.h" + +//helper macros +#define REGISTER_STRATEGY(c) qRegisterMetaType(#c) + +//defines +#define SCRATCH_PAD_SIZE 2000 + +#define KERNEL_PATH_POSTFIX "/lib/Kernels" +#define SCENARIO_PATH_POSTFIX "/config/Scenarios" + +/*************************************************************************************************/ +/** + * @brief Does the actual work of BIP module + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2020/08/22(1399/6/1) + */ +/*************************************************************************************************/ +class BipCore : public QObject +{ + Q_OBJECT + +private: + QList _queues; + + cl::CommandQueue _clQueue; + cl::Context _clContext; + cl::Buffer* _scratchPad; + + OpenClHelper _openCLHelper; + + QString _kernelsFolder; + QString _scenariosFolder; + + UsPacket _dataStorage; + BipImage_t _outputImage; + + QString getApplicationHomePath(); + QString getStrategyPath(EImageMode::eImageMode imageMode); + void createStrategyQueues(ProcessQueueFactory* queueFactory, QString inputPath); + QStringList getQueueDestinations(QString line); + bool queueIsNull(ProcessQueue* queue); + bool shouldSendImageToOutside(QString destination); + void process(cl::Image* clFrames, const UsMetadataBag& metaData, cl::Buffer* _scratchPad); + void dispatcher(cl::Image* frame, UsMetadataBag metadata, EDataType::eDataType dataType); + void connectQueuesStrategyParam(ProcessQueue* queue); + void connectQueuesTransientData(ProcessQueue* queue); + ProcessQueue* selectQueueByName(QString name); + void connectQueueOutputToAnotherQueue(ProcessQueue* source, QString destinationName); + void connectQueueOutputToCore(ProcessQueue* source); + void registerStrategies(); + +public: + BipCore(); + ~BipCore(); + + void init(); + void changeMode(const EImageMode::eImageMode& imageMode); + void changeStrategyParam(KernelInput_t scenarioParams); + void newData(const UsPacket& data); + +signals: + void strategyParamReady(KernelInput_t parameters); + void outputReady(const UsPacket cineData, const BipImage_t outputImage); + + //uncrustify off +public slots: +//uncrustify on + + void newQueueTransientData(const QByteArray transienData, UsMetadataBag& metadata); + void newQueueOutputData(cl::Image* frames, + UsMetadataBag& metadata, + cl::Buffer* _scratchPad); +}; + +#endif //BIPCORE_H diff --git a/include/model/backendImageProcessor/core/algorithm/ScanConversionAlg.h b/include/model/backendImageProcessor/core/algorithm/ScanConversionAlg.h new file mode 100644 index 0000000..c24316b --- /dev/null +++ b/include/model/backendImageProcessor/core/algorithm/ScanConversionAlg.h @@ -0,0 +1,50 @@ +#ifndef SCANCONVERSIONALG_H +#define SCANCONVERSIONALG_H + +#include "model/backendImageProcessor/dtoInternal/KernelInput.h" +#include "model/backendImageProcessor/core/algorithm/ScanConversionOutput.h" + +/*************************************************************************************************/ +/** + * @brief utils class for scan conversion method, as this method will be used at least in two + * places having them here is a good choice + */ +/*************************************************************************************************/ +class ScanConversionAlg +{ +private: + static ScanConversionOutput_t linear(BipScanConversionConfig_t params, QVector pixelXPos, + QVector pixelZPos); + + static ScanConversionOutput_t virtualConvex(BipScanConversionConfig_t params, + QVector pixelXPos, + QVector pixelZPos); + + static ScanConversionOutput_t convex(BipScanConversionConfig_t params, QVector pixelXPos, + QVector pixelZPos); + +public: + static QPair, QVector > makeGrid(BipScanConversionConfig_t params); + + static ScanConversionOutput_t scanConversion(BipScanConversionConfig_t params); + + static QPair, QVector > virtualScanConversion(QVector pixelXPos, + QVector pixelZPos, + float steering, + float virtualOriginalZ, + float startDepth, + float depth, + float vcMaxTheta); + + static QPair, QVector > convexScanConversion( + QVector pixelXPos, + QVector pixelZPos, + float steering, + float angle, + float fieldOfView, + float probeRadius, + float startDepth, + float depth); +}; + +#endif //SCANCONVERSIONALG_H diff --git a/include/model/backendImageProcessor/core/algorithm/ScanConversionOutput.h b/include/model/backendImageProcessor/core/algorithm/ScanConversionOutput.h new file mode 100644 index 0000000..ce42d8b --- /dev/null +++ b/include/model/backendImageProcessor/core/algorithm/ScanConversionOutput.h @@ -0,0 +1,14 @@ +#ifndef SCANCONVERSIONOUTPUT_H +#define SCANCONVERSIONOUTPUT_H + +#include + +struct ScanConversionOutput_t +{ + QVector scanAzPos; + QVector scanAxPos; + QVector gridAzPos; + QVector gridAxPos; +}; + +#endif //SCANCONVERSIONOUTPUT_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/B/Cri.h b/include/model/backendImageProcessor/core/kernelHelper/B/Cri.h new file mode 100644 index 0000000..b468cd7 --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/B/Cri.h @@ -0,0 +1,36 @@ +#ifndef CRI_H +#define CRI_H + +#include + +#include "model/backendImageProcessor/core/BaseStrategy.h" +#include "model/backendImageProcessor/core/kernelHelper/kernelDto/CriDto.h" + +#define CRI_MAX_BUFFER_SIZE 11 + +class Cri : public BaseStrategy +{ + Q_OBJECT + +public: + Q_INVOKABLE Cri(const cl::Context& context, + const cl::CommandQueue& queue, + const QString kernelPath); + + virtual void cpuProcess(KernelInput_t parameters) override; + virtual void finalize() override; + +private: + cl::KernelFunctor _kernelFunctor; + Cri_t _kernelParameters; + QList _criBuffer; + int counter = 0; + + virtual cl::Image* gpuProcess(cl::Image* frames, + UsMetadataBag& metadataBag, + cl::Buffer* scrathPad) override; +}; + +#endif //CRI_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/B/DynamicContrastB.h b/include/model/backendImageProcessor/core/kernelHelper/B/DynamicContrastB.h new file mode 100644 index 0000000..9483e59 --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/B/DynamicContrastB.h @@ -0,0 +1,40 @@ +#ifndef DYNAMICCONTRASTB_H +#define DYNAMICCONTRASTB_H + +#include + +#include "model/backendImageProcessor/core/BaseStrategy.h" +#include "model/backendImageProcessor/core/kernelHelper/kernelDto/DynamicContrastKernelDto.h" + +/*************************************************************************************************/ +/** + * @brief The class is responsible interfacing with dynamic contrast opencl kernel + * @author Hessamoddin Hediyehloo(h-4nd-h) + * @date 2020/10/19(1399/7/28) + */ +/*************************************************************************************************/ +class DynamicContrastB : public BaseStrategy +{ + Q_OBJECT + +private: + cl::KernelFunctor _kernelFunctor; + DynamicContrast_t _kernelParameters; + + virtual cl::Image* gpuProcess(cl::Image* frames, UsMetadataBag& metadataBag, + cl::Buffer* scrathPad) override; + +protected: + virtual void finalize() override; + +public: + Q_INVOKABLE DynamicContrastB(const cl::Context& context, + const cl::CommandQueue& queue, + const QString kernelPath); + + ~DynamicContrastB(); + + virtual void cpuProcess(KernelInput_t parameters) override; +}; + +#endif //DYNAMICCONTRASTB_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/B/EnhanceB.h b/include/model/backendImageProcessor/core/kernelHelper/B/EnhanceB.h new file mode 100644 index 0000000..7704745 --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/B/EnhanceB.h @@ -0,0 +1,47 @@ +#ifndef ENHANCEB_H +#define ENHANCEB_H + +#include +#include + +#include "model/backendImageProcessor/core/BaseStrategy.h" +#include "model/backendImageProcessor/core/kernelHelper/kernelDto/EnhanceKernelDto.h" + +/*************************************************************************************************/ +/** + * @brief The class is responsible interfacing with enhance opencl kernel + * @author Hessamoddin Hediyehloo(h-4nd-h) + * @date 2020/10/21(1399/7/30) + */ +/*************************************************************************************************/ +class EnhanceB : public BaseStrategy +{ + Q_OBJECT + +private: + cl::KernelFunctor _kernelFunctor; + + Enhance_t _kernelParameters; + + bool _run; + + cl::Buffer* _filter; + + virtual cl::Image* gpuProcess(cl::Image* frames, + UsMetadataBag& metadataBag, + cl::Buffer* scrathPad) override; + +protected: + virtual void finalize() override; + +public: + Q_INVOKABLE EnhanceB(const cl::Context& context, + const cl::CommandQueue& queue, + const QString kernelPath); + + ~EnhanceB(); + + virtual void cpuProcess(KernelInput_t parameters) override; +}; + +#endif //ENHANCEB_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/B/FrameFilter.h b/include/model/backendImageProcessor/core/kernelHelper/B/FrameFilter.h new file mode 100644 index 0000000..2eba333 --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/B/FrameFilter.h @@ -0,0 +1,44 @@ +#ifndef FRAMEFILTER_H +#define FRAMEFILTER_H + +#include +#include + +#include "model/backendImageProcessor/core/BaseStrategy.h" +#include "model/backendImageProcessor/core/kernelHelper/kernelDto/PersistKernelDto.h" + +/*************************************************************************************************/ +/** + * @brief The class is responsible interfacing with FrameFilter opencl kernel + * @author Hessamoddin Hediyehloo(h-4nd-h) + * @date 2020/11/11(1399/8/20) + */ +/*************************************************************************************************/ +class FrameFilter : public BaseStrategy +{ + Q_OBJECT + +public: + Q_INVOKABLE FrameFilter(const cl::Context& context, + const cl::CommandQueue& queue, + const QString kernelPath); + virtual void cpuProcess(KernelInput_t parameters) override; + virtual void finalize() override; + +private: + cl::KernelFunctor _kernelFunctor; + virtual cl::Image* gpuProcess(cl::Image* frames, + UsMetadataBag& metadataBag, + cl::Buffer* scrathPad) override; + + Persist_t _kernelParameters; + + QList _sum; + QList > _last; + QList _counter; + + int _fifoLength; +}; + +#endif //FRAMEFILTER_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/B/GrayMapB.h b/include/model/backendImageProcessor/core/kernelHelper/B/GrayMapB.h new file mode 100644 index 0000000..a9f2117 --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/B/GrayMapB.h @@ -0,0 +1,41 @@ +#ifndef GRAYMAPB_H +#define GRAYMAPB_H + +#include +#include + +#include "model/backendImageProcessor/core/BaseStrategy.h" +#include "model/backendImageProcessor/core/kernelHelper/kernelDto/GrayMapKernelDto.h" + +/*************************************************************************************************/ +/** + * @brief The class is responsible interfacing with graymap opencl kernel + * @author Hessamoddin Hediyehloo(h-4nd-h) + * @date 2020/10/26(1399/8/5) + */ +/*************************************************************************************************/ +class GrayMapB : public BaseStrategy +{ + Q_OBJECT + +public: + Q_INVOKABLE GrayMapB(const cl::Context& context, + const cl::CommandQueue& queue, + const QString kernelPath); + + virtual void cpuProcess(KernelInput_t parameters) override; + virtual void finalize() override; + +private: + cl::KernelFunctor _kernelFunctor; + + GrayMap_t _kernelParameters; + + cl::Buffer* _grayMap; + + virtual cl::Image* gpuProcess(cl::Image* frames, + UsMetadataBag& metadataBag, + cl::Buffer* scrathPad) override; +}; + +#endif //GRAYMAPB_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/B/Persist.h b/include/model/backendImageProcessor/core/kernelHelper/B/Persist.h new file mode 100644 index 0000000..1008d2d --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/B/Persist.h @@ -0,0 +1,44 @@ +#ifndef PERSIST_H +#define PERSIST_H + +#include +#include + +#include "model/backendImageProcessor/core/BaseStrategy.h" +#include "model/backendImageProcessor/core/kernelHelper/kernelDto/PersistKernelDto.h" + +/*************************************************************************************************/ +/** + * @brief The class is responsible interfacing with Persist opencl kernel + * @author Hessamoddin Hediyehloo(h-4nd-h) + * @date 2020/11/11(1399/8/20) + */ +/*************************************************************************************************/ +class Persist : public BaseStrategy +{ + Q_OBJECT + +public: + Q_INVOKABLE Persist(const cl::Context& context, + const cl::CommandQueue& queue, + const QString kernelPath); + virtual void cpuProcess(KernelInput_t parameters) override; + virtual void finalize() override; + +private: + cl::KernelFunctor _kernelFunctor; + virtual cl::Image* gpuProcess(cl::Image* frames, + UsMetadataBag& metadataBag, + cl::Buffer* scrathPad) override; + + Persist_t _kernelParameters; + + cl::Image* _sum; + QList _last; + int _counter; + + int _fifoLength; +}; + +#endif //PERSIST_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/B/RejectionB.h b/include/model/backendImageProcessor/core/kernelHelper/B/RejectionB.h new file mode 100644 index 0000000..09216d7 --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/B/RejectionB.h @@ -0,0 +1,41 @@ +#ifndef REJECTIONB_H +#define REJECTIONB_H + +#include +#include + +#include "model/backendImageProcessor/core/BaseStrategy.h" +#include "model/backendImageProcessor/core/kernelHelper/kernelDto/RejectionKernelDto.h" + +/*************************************************************************************************/ +/** + * @brief The class is responsible interfacing with Reject opencl kernel + * @author Hessamoddin Hediyehloo(h-4nd-h) + * @date 2020/10/24(1399/8/3) + */ +/*************************************************************************************************/ + +class RejectionB : public BaseStrategy +{ + Q_OBJECT + +public: + Q_INVOKABLE RejectionB(const cl::Context& context, + const cl::CommandQueue& queue, + const QString kernelPath); + + virtual void cpuProcess(KernelInput_t parameters) override; + virtual void finalize() override; + +private: + cl::KernelFunctor _kernelFunctor; + Rejection_t _kernelParameters; + + float _rejectionThr; + + virtual cl::Image* gpuProcess(cl::Image* frames, + UsMetadataBag& metadataBag, + cl::Buffer* scrathPad) override; +}; + +#endif //REJECTIONB_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/B/ScanConversionB.h b/include/model/backendImageProcessor/core/kernelHelper/B/ScanConversionB.h new file mode 100644 index 0000000..9e3cbec --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/B/ScanConversionB.h @@ -0,0 +1,46 @@ +#ifndef SCANCONVERSION_H +#define SCANCONVERSION_H + +#include +#include + +#include "model/backendImageProcessor/core/BaseStrategy.h" +#include "model/backendImageProcessor/core/kernelHelper/kernelDto/ScanConversionKernelDto.h" + +class ScanConversionB : public BaseStrategy +{ + Q_OBJECT + +public: + Q_INVOKABLE ScanConversionB(const cl::Context& context, + const cl::CommandQueue& queue, + const QString kernelPath); + + virtual void cpuProcess(KernelInput_t parameters) override; + virtual void finalize() override; + +private: + cl::KernelFunctor _kernelFunctor; + + ScanConversion_t _kernelParameters; + + void calcParams(int frameNumber); + + QList _configs; + quint64 _width; + quint64 _height; + + quint8 lastFrameCounter; + + cl::Buffer* _gridX; + cl::Buffer* _gridZ; + cl::Buffer* _queryX; + cl::Buffer* _queryZ; + + virtual cl::Image* gpuProcess(cl::Image* frames, + UsMetadataBag& metadataBag, + cl::Buffer* scrathPad) override; +}; + +#endif //SCANCONVERSION_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/B/TintMapB.h b/include/model/backendImageProcessor/core/kernelHelper/B/TintMapB.h new file mode 100644 index 0000000..e533fe9 --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/B/TintMapB.h @@ -0,0 +1,41 @@ +#ifndef TINTMAP_H +#define TINTMAP_H + +#include +#include + +#include "model/backendImageProcessor/core/BaseStrategy.h" +#include "model/backendImageProcessor/core/kernelHelper/kernelDto/TintMapKernelDto.h" + +/*************************************************************************************************/ +/** + * @brief The class is responsible interfacing with tinemap opencl kernel + * @author Hessamoddin Hediyehloo(h-4nd-h) + * @date 2020/10/26(1399/8/5) + */ +/*************************************************************************************************/ +class TintMapB : public BaseStrategy +{ + Q_OBJECT + +public: + Q_INVOKABLE TintMapB(const cl::Context& context, + const cl::CommandQueue& queue, + const QString kernelPath); + + virtual void cpuProcess(KernelInput_t parameters) override; + virtual void finalize() override; + +private: + cl::KernelFunctor _kernelFunctor; + + TintMap_t _kernelParameters; + + cl::Buffer* _tintMap; + + virtual cl::Image* gpuProcess(cl::Image* frames, + UsMetadataBag& metadataBag, + cl::Buffer* scrathPad) override; +}; + +#endif //TINTMAP_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/kernelDto/CriDto.h b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/CriDto.h new file mode 100644 index 0000000..d791d61 --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/CriDto.h @@ -0,0 +1,13 @@ +#ifndef CRIDTO_H +#define CRIDTO_H +#include "model/backendImageProcessor/utils/OpenClHelper.h" +typedef struct Cri_t +{ + cl_int criFilterMode; + cl_int frameCntr; + cl_int scenarioFrameNumber; + cl_float zeroSteeringFrameWeight; + cl_float nonZeroSteeringFrameWeight; +}Cri_t; + +#endif //CRIDTO_H \ No newline at end of file diff --git a/include/model/backendImageProcessor/core/kernelHelper/kernelDto/DynamicContrastKernelDto.h b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/DynamicContrastKernelDto.h new file mode 100644 index 0000000..264cbbe --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/DynamicContrastKernelDto.h @@ -0,0 +1,13 @@ +#ifndef DYNAMICCONTRASTKERNELDTO_H +#define DYNAMICCONTRASTKERNELDTO_H + +#include "model/backendImageProcessor/utils/OpenClHelper.h" + +typedef struct DynamicContrast_t +{ + cl_int gain; + cl_int transformType; //0 : log, 1 : power + cl_float gamma; +}DynamicContrast_t; + +#endif //DYNAMICCONTRASTKERNELDTO_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/kernelDto/EnhanceKernelDto.h b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/EnhanceKernelDto.h new file mode 100644 index 0000000..3b84315 --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/EnhanceKernelDto.h @@ -0,0 +1,14 @@ +#ifndef ENHANCEKERNELDTO_H +#define ENHANCEKERNELDTO_H + +#include "model/backendImageProcessor/utils/OpenClHelper.h" + +typedef struct Enhance_t +{ + cl_int filterWidth; + cl_int filterHeight; + cl_int width; + cl_int height; +}Enhance_t; + +#endif //ENHANCEKERNELDTO_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/kernelDto/GrayMapKernelDto.h b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/GrayMapKernelDto.h new file mode 100644 index 0000000..a58fcba --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/GrayMapKernelDto.h @@ -0,0 +1,12 @@ +#ifndef GRAYMAPKERNELDTO_H +#define GRAYMAPKERNELDTO_H + +#include "model/backendImageProcessor/utils/OpenClHelper.h" + +typedef struct GrayMap_t +{ +} + +GrayMap_t; + +#endif //GRAYMAPKERNELDTO_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/kernelDto/PersistKernelDto.h b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/PersistKernelDto.h new file mode 100644 index 0000000..c5e43d6 --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/PersistKernelDto.h @@ -0,0 +1,12 @@ +#ifndef PERSISTKERNELDTO_H +#define PERSISTKERNELDTO_H + +#include "model/backendImageProcessor/utils/OpenClHelper.h" + +typedef struct Persist_t +{ + cl_int fifoLength; + cl_int mode; +}Persist_t; + +#endif //PERSISTKERNELDTO_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/kernelDto/RejectionKernelDto.h b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/RejectionKernelDto.h new file mode 100644 index 0000000..656d824 --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/RejectionKernelDto.h @@ -0,0 +1,11 @@ +#ifndef REJECTIONKERNELDTO_H +#define REJECTIONKERNELDTO_H + +#include "model/backendImageProcessor/utils/OpenClHelper.h" + +typedef struct Rejection_t +{ + cl_int rejectThr; +}Rejection_t; + +#endif //REJECTIONKERNELDTO_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/kernelDto/ScanConversionKernelDto.h b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/ScanConversionKernelDto.h new file mode 100644 index 0000000..4495406 --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/ScanConversionKernelDto.h @@ -0,0 +1,15 @@ +#ifndef SCANCONVERSIONKERNELDTO_H +#define SCANCONVERSIONKERNELDTO_H + +#include "model/backendImageProcessor/utils/OpenClHelper.h" + +typedef struct ScanConversion_t +{ + cl_int width; + cl_int gridXSize; + cl_int gridZSize; + cl_float dx; + cl_float dz; +}ScanConversion_t; + +#endif //SCANCONVERSIONKERNELDTO_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/kernelDto/SriKernelDto.h b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/SriKernelDto.h new file mode 100644 index 0000000..7fe664e --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/SriKernelDto.h @@ -0,0 +1,16 @@ +#ifndef SRIKERNELDTO_H +#define SRIKERNELDTO_H + +#include "model/backendImageProcessor/utils/OpenClHelper.h" + +typedef struct Sri_t +{ + cl_int state; + cl_int windowSize; + cl_float alpha; + cl_int algorithmSelector; + cl_int width; + cl_int height; +}Sri_t; + +#endif //SRIKERNELDTO_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/kernelDto/TintMapKernelDto.h b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/TintMapKernelDto.h new file mode 100644 index 0000000..4d691c5 --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/kernelDto/TintMapKernelDto.h @@ -0,0 +1,12 @@ +#ifndef TINTMAPKERNELDTO_H +#define TINTMAPKERNELDTO_H + +#include "model/backendImageProcessor/utils/OpenClHelper.h" + +typedef struct TintMap_t +{ +} + +TintMap_t; + +#endif //TINTMAPKERNELDTO_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/misc/PreProcess.h b/include/model/backendImageProcessor/core/kernelHelper/misc/PreProcess.h new file mode 100644 index 0000000..9fb276f --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/misc/PreProcess.h @@ -0,0 +1,38 @@ +#ifndef PREPROCESS_H +#define PREPROCESS_H + +#include +#include + +#include "model/backendImageProcessor/core/BaseStrategy.h" + +/*************************************************************************************************/ +/** + * @brief The class is responsible interfacing with PreProcess opencl kernel + * @author Hessamoddin Hediyehloo(h-4nd-h) + * @date 2020/11/07(1399/8/17) + */ +/*************************************************************************************************/ +class PreProcess : public BaseStrategy +{ + Q_OBJECT + +public: + Q_INVOKABLE PreProcess(const cl::Context& context, + const cl::CommandQueue& queue, + const QString kernelPath); + + virtual void cpuProcess(KernelInput_t parameters) override; + virtual void finalize() override; + +private: + cl::KernelFunctor _kernelFunctor; + + bool run; + + virtual cl::Image* gpuProcess(cl::Image* frames, + UsMetadataBag& metadataBag, + cl::Buffer* scrathPad) override; +}; + +#endif //PREPROCESS_H diff --git a/include/model/backendImageProcessor/core/kernelHelper/misc/Sri.h b/include/model/backendImageProcessor/core/kernelHelper/misc/Sri.h new file mode 100644 index 0000000..82b0195 --- /dev/null +++ b/include/model/backendImageProcessor/core/kernelHelper/misc/Sri.h @@ -0,0 +1,42 @@ +#ifndef SRI_H +#define SRI_H + +#include +#include + +#include "model/backendImageProcessor/core/BaseStrategy.h" +#include "model/backendImageProcessor/core/kernelHelper/kernelDto/SriKernelDto.h" + +/*************************************************************************************************/ +/** + * @brief The class is responsible interfacing with Sri opencl kernel + * @author Hessamoddin Hediyehloo(h-4nd-h) + * @date 2020/10/24(1399/8/3) + */ +/*************************************************************************************************/ +class Sri : public BaseStrategy +{ + Q_OBJECT + +public: + Q_INVOKABLE Sri(const cl::Context& context, + const cl::CommandQueue& queue, + const QString kernelPath); + + virtual void cpuProcess(KernelInput_t input) override; + virtual void finalize() override; + +private: + cl::KernelFunctor _kernelFunctor; + + Sri_t _kernelParameters; + + bool _run; + + virtual cl::Image* gpuProcess(cl::Image* frames, + UsMetadataBag& metadata, + cl::Buffer* scrathPad) override; +}; + +#endif //SRI_H diff --git a/include/model/backendImageProcessor/core/process/ProcessConfig.h b/include/model/backendImageProcessor/core/process/ProcessConfig.h new file mode 100644 index 0000000..2c5900c --- /dev/null +++ b/include/model/backendImageProcessor/core/process/ProcessConfig.h @@ -0,0 +1,20 @@ +#ifndef PROCESSCONFIG_H +#define PROCESSCONFIG_H + +#include + +#include "model/backendImageProcessor/core/strategy/StrategyConfig.h" + +class ProcessConfig +{ +private: + QString _connection; + +public: + ProcessConfig(QString connection); + + bool isEmpty(); + QList getFields(); +}; + +#endif //PROCESSCONFIG_H diff --git a/include/model/backendImageProcessor/core/process/ProcessQueue.h b/include/model/backendImageProcessor/core/process/ProcessQueue.h new file mode 100644 index 0000000..b7a9957 --- /dev/null +++ b/include/model/backendImageProcessor/core/process/ProcessQueue.h @@ -0,0 +1,62 @@ +#ifndef PROCESSQUEUE_H +#define PROCESSQUEUE_H + +#include + +#include "model/backendImageProcessor/core/strategy/StrategyQueue.h" +#include "model/ultrasoundModule/metadata/UsMetadataBag.h" +#include "model/ultrasoundModule/metadata/UsBaseMetadata.h" +#include "model/ultrasoundModule/metadata/BipMetadata.h" + +class ProcessQueue : public QObject +{ + Q_OBJECT + +protected: + QString _name; + StrategyQueue _queue; + + cl::CommandQueue _clQueue; + +public: + ProcessQueue() + { + } + + virtual bool create(const QString name, const QString connection) = 0; + + void init(const cl::Context& clContext, + const cl::CommandQueue& clQueue, + const QString kernelsFolder) + { + _clQueue = clQueue; + _queue.init(clContext, clQueue, kernelsFolder); + } + + QString getName() + { + return _name; + } + +signals: + void strategyParamReady(KernelInput_t parameters); + void transientOutputReady(QByteArray transient, UsMetadataBag& metadata); + + void processedOutputReady(cl::Image* frames, + UsMetadataBag& metadata, + cl::Buffer* _scratchPad); + +//uncrustify off +public slots: +//uncrustify on + virtual void process(cl::Image* clFrames, UsMetadataBag& metadata, cl::Buffer* _scratchPad) = 0; + virtual void newStrategyParam(KernelInput_t parameters) = 0; + virtual void newProcessedData(cl::Image* frames, + UsMetadataBag& metadata, + cl::Buffer* _scratchPad) = 0; + virtual void newTransientData(cl::Image* frames, + UsMetadataBag& metadata, + cl::Buffer* _scratchPad) = 0; +}; + +#endif //PROCESSQUEUE_H diff --git a/include/model/backendImageProcessor/core/process/ProcessQueueFactory.h b/include/model/backendImageProcessor/core/process/ProcessQueueFactory.h new file mode 100644 index 0000000..f6b7bda --- /dev/null +++ b/include/model/backendImageProcessor/core/process/ProcessQueueFactory.h @@ -0,0 +1,26 @@ +#ifndef STRATEGYQUEUEFACTORY_H +#define STRATEGYQUEUEFACTORY_H + +#include + +#include "model/backendImageProcessor/core/process/ProcessQueue.h" +#include "model/backendImageProcessor/core/scenario/ScenarioConfig.h" + +class ProcessQueueFactory +{ +public: + ProcessQueueFactory() + { + } + + virtual ~ProcessQueueFactory() + { + } + + virtual ProcessQueue* createStrategyQueue(const ScenarioConfig& config, + cl::Context clContext, + cl::CommandQueue clQueue, + QString kernelsFolder) = 0; +}; + +#endif //STRATEGYQUEUEFACTORY_H diff --git a/include/model/backendImageProcessor/core/process/twoD/TwoDProcessQueue.h b/include/model/backendImageProcessor/core/process/twoD/TwoDProcessQueue.h new file mode 100644 index 0000000..1056a1b --- /dev/null +++ b/include/model/backendImageProcessor/core/process/twoD/TwoDProcessQueue.h @@ -0,0 +1,33 @@ +#ifndef TWODSTRATEGYQUEUE_H +#define TWODSTRATEGYQUEUE_H + +#include +#include + +#include "model/backendImageProcessor/core/process/ProcessQueue.h" + +class TwoDProcessQueue : public ProcessQueue +{ + Q_OBJECT + +private: + QByteArray readProcessedImageFromGpu(cl::Image* frame, UsMetadataBag& metadataBag); + void registerStrategies(); + +public: + bool create(const QString name, const QString connection) override; + + void process(cl::Image* inputFrame, UsMetadataBag& metadataBag, + cl::Buffer* scratchPad) override; + +//uncrustify off +public slots: + void newStrategyParam(KernelInput_t parameters) override; + void newProcessedData(cl::Image* frame, UsMetadataBag& metadataBag, + cl::Buffer* scratchPad) override; + void newTransientData(cl::Image* frame, UsMetadataBag& metadataBag, + cl::Buffer* scratchPad) override; +//uncrustify on +}; + +#endif //STRATEGYQUEUE_H diff --git a/include/model/backendImageProcessor/core/process/twoD/TwoDProcessQueueFactory.h b/include/model/backendImageProcessor/core/process/twoD/TwoDProcessQueueFactory.h new file mode 100644 index 0000000..314743b --- /dev/null +++ b/include/model/backendImageProcessor/core/process/twoD/TwoDProcessQueueFactory.h @@ -0,0 +1,19 @@ +#ifndef TWODSTRATEGYQUEUEFACTORY_H +#define TWODSTRATEGYQUEUEFACTORY_H + +#include "model/backendImageProcessor/core/process/ProcessQueueFactory.h" +#include "model/backendImageProcessor/core/process/twoD/TwoDProcessQueue.h" + +class TwoDProcessQueueFactory : public ProcessQueueFactory +{ +public: + TwoDProcessQueueFactory(); + ~TwoDProcessQueueFactory() override; + + ProcessQueue* createStrategyQueue(const ScenarioConfig& config, + cl::Context clContext, + cl::CommandQueue clQueue, + QString kernelsFolder) override; +}; + +#endif //TWODSTRATEGYQUEUEFACTORY_H diff --git a/include/model/backendImageProcessor/core/scenario/ScenarioConfig.h b/include/model/backendImageProcessor/core/scenario/ScenarioConfig.h new file mode 100644 index 0000000..90b0ec8 --- /dev/null +++ b/include/model/backendImageProcessor/core/scenario/ScenarioConfig.h @@ -0,0 +1,18 @@ +#ifndef SCENARIOCONFIG_H +#define SCENARIOCONFIG_H + +#include + +class ScenarioConfig +{ + QString _connection; + +public: + ScenarioConfig(QString connection); + + QString getQueueName() const; + QString getQueueFunctionality() const; + QStringList getQueueDestinations() const; +}; + +#endif //SCENARIOCONFIG_H diff --git a/include/model/backendImageProcessor/core/strategy/StrategyConfig.h b/include/model/backendImageProcessor/core/strategy/StrategyConfig.h new file mode 100644 index 0000000..8ffb3f2 --- /dev/null +++ b/include/model/backendImageProcessor/core/strategy/StrategyConfig.h @@ -0,0 +1,18 @@ +#ifndef STRATEGYCONFIG_H +#define STRATEGYCONFIG_H + +#include + +class StrategyConfig +{ +private: + QString _connection; + +public: + StrategyConfig(QString connection); + + QString getStrategyName() const; + bool hasTransientProbe() const; +}; + +#endif //STRATEGYCONFIG_H diff --git a/include/model/backendImageProcessor/core/strategy/StrategyQueue.h b/include/model/backendImageProcessor/core/strategy/StrategyQueue.h new file mode 100644 index 0000000..1c10a50 --- /dev/null +++ b/include/model/backendImageProcessor/core/strategy/StrategyQueue.h @@ -0,0 +1,44 @@ +#ifndef STRATEGYQUEUE_H +#define STRATEGYQUEUE_H + +#include + +#include "model/backendImageProcessor/core/BaseStrategy.h" +#include "model/backendImageProcessor/core/process/ProcessConfig.h" + +class ProcessQueue; + +class StrategyQueue : public QObject +{ +private: + QList _queue; + + cl::Context _clContext; + cl::CommandQueue _clQueue; + + QString _kernelsFolder; + + bool queueHasMoreThanOneStrategy(); + void connectLastStrategyToPreviousStrategy(); + + BaseStrategy* createStrategy(QString name); + void appendStrategy(BaseStrategy* strategy); + + void connectStrategyTransientOutput(BaseStrategy* strategy, ProcessQueue* owner); + void connectLastStrategyOutput(BaseStrategy* strategy, ProcessQueue* owner); + void connectStrategyParameterPath(BaseStrategy* strategy, ProcessQueue* owner); + void disconnectSignals(); + +public: + StrategyQueue(); + ~StrategyQueue(); + + void init(const cl::Context& clContext, + const cl::CommandQueue& clQueue, + const QString kernelsFolder); + void create(ProcessConfig processConfig, ProcessQueue* parent); + void process(cl::Image* inputFrame, UsMetadataBag& metadataBag, + cl::Buffer* scratchPad); +}; + +#endif //STRATEGYQUEUE_H diff --git a/include/model/backendImageProcessor/dto/BipImage.h b/include/model/backendImageProcessor/dto/BipImage.h new file mode 100644 index 0000000..f1d600c --- /dev/null +++ b/include/model/backendImageProcessor/dto/BipImage.h @@ -0,0 +1,19 @@ +#ifndef BIPIMAGE_H +#define BIPIMAGE_H + +#include + +#include "model/ultrasoundModule/metadata/UsMetadataBag.h" + +typedef struct BipImage_t +{ + QImage bImage; + QImage mImage; + QImage cImage; + QImage cmImage; + UsMetadataBag metaData; +}BipImage_t; + +Q_DECLARE_METATYPE(BipImage_t) + +#endif //BIPIMAGE_H diff --git a/include/model/backendImageProcessor/dto/BipProbeProperties.h b/include/model/backendImageProcessor/dto/BipProbeProperties.h new file mode 100644 index 0000000..c73da37 --- /dev/null +++ b/include/model/backendImageProcessor/dto/BipProbeProperties.h @@ -0,0 +1,11 @@ +#ifndef BIPPROBEPROPERTIES_H +#define BIPPROBEPROPERTIES_H + +typedef struct BipProbeProperties_t +{ + bool linear; + float radius; + float fieldOfView; +}BipProbeProperties_t; + +#endif // BIPPROBEPROPERTIES_H diff --git a/include/model/backendImageProcessor/dtoInternal/BipInput.h b/include/model/backendImageProcessor/dtoInternal/BipInput.h new file mode 100644 index 0000000..b969594 --- /dev/null +++ b/include/model/backendImageProcessor/dtoInternal/BipInput.h @@ -0,0 +1,120 @@ +#ifndef BIPINPUT_H +#define BIPINPUT_H + +#include + +#include "model/backendImageProcessor/dto/BipProbeProperties.h" +#include "model/backendImageProcessor/dtoInternal/BipScanConversionConfig.h" + +struct BipInput_t +{ + //scan conv + QList scanConversionConfig; + uint outputWidth; + uint outputHeight; + //reject + int rejectBThreshold; + int rejectMThreshold; + //enhance + int enhanceBSelector; + int enhanceMSelector; + //dynamic contrast + int dynamicContrastBSelector; + int dynamicContrastMSelector; + int dynamicContrastBGain; + int dynamicContrastMGain; + //sri + int sri; + //cri + int cri; + int criFilterMode; + //grayMap + QList grayMapB; + QList grayMapM; + //tintmap + int tintMapBSelector; + int tintMapMSelector; + //persist + int persist; + //frame filter + int frameFilterMode; + + BipInput_t() + { + } + + BipInput_t(ScenGenSoftwareOutput_t scenParams) + { + for(auto i = 0; i < scenParams.scanConversionProps.length(); i++) + { + scanConversionConfig.append(BipScanConversionConfig_t(scenParams.scanConversionProps[i])); + } + + outputWidth = scenParams.outputWidth; + outputHeight = scenParams.outputHeight; + + //reject + rejectBThreshold = scenParams.rejectB; + + //sri + sri = scenParams.sri; + + //enhance + enhanceBSelector = scenParams.enhanceB; + + //dynamic contrast + dynamicContrastBSelector = scenParams.dynamicContrastBSelector; + dynamicContrastBGain = scenParams.gainB; + + //graymap + grayMapB = scenParams.grayMapB; + grayMapM = scenParams.grayMapM; + + //tintmap + tintMapBSelector = scenParams.tintMapBSelector; + tintMapMSelector = scenParams.tintMapMSelector; + + cri = scenParams.cri; + criFilterMode = scenParams.criFilterMode; + persist = scenParams.persist; + frameFilterMode = scenParams.frameFilterMode; + } + + void operator= (const BipInput_t& b) + { + scanConversionConfig.append(b.scanConversionConfig); + for(auto i = 0; i < b.grayMapB.length(); i++) + { + grayMapB.push_back(b.grayMapB[i]); + } + grayMapM.append(b.grayMapM); + + outputWidth = b.outputWidth; + outputHeight = b.outputHeight; + + rejectBThreshold = b.rejectBThreshold; + rejectMThreshold = b.rejectMThreshold; + + enhanceBSelector = b.enhanceBSelector; + enhanceMSelector = b.enhanceMSelector; + + dynamicContrastBSelector = b.dynamicContrastBSelector; + dynamicContrastMSelector = b.dynamicContrastMSelector; + dynamicContrastBGain = b.dynamicContrastBGain; + dynamicContrastMGain = b.dynamicContrastMGain; + + sri = b.sri; + + cri = b.cri; + criFilterMode = b.criFilterMode; + + tintMapBSelector = b.tintMapBSelector; + tintMapMSelector = b.tintMapMSelector; + + persist = b.persist; + + frameFilterMode = b.frameFilterMode; + } +}; + +#endif //BIPINPUT_H diff --git a/include/model/backendImageProcessor/dtoInternal/BipScanConversionConfig.h b/include/model/backendImageProcessor/dtoInternal/BipScanConversionConfig.h new file mode 100644 index 0000000..751dd09 --- /dev/null +++ b/include/model/backendImageProcessor/dtoInternal/BipScanConversionConfig.h @@ -0,0 +1,79 @@ +#ifndef BIPSCANCONVERSIONCONFIG_H +#define BIPSCANCONVERSIONCONFIG_H + +#include "model/scenarioGenerator/dto/software/SoftwareOutput.h" + +struct BipScanConversionConfig_t { + bool linear; + float probeRadius; + float fieldOfView; + float probeFieldOfView; + float virtualOriginalZ; + float bMinScanAx; + float bMinScanAz; + float bMaxScanAx; + float bMaxScanAz; + float minScanAx; + float minScanAz; + float maxScanAx; + float steering; + quint32 rxLineNo; + quint32 rxFocusPointNo; + float rxLineDaz; + float rxPointDax; + bool virtualConvex; + float vcMaxTheta; + float angle; + Pixel_t pixel; + + BipScanConversionConfig_t(ScenGenScanConversionConfig_t config) + { + this->linear = config.linear; + this->probeRadius = config.probeRadius; + this->fieldOfView = config.fieldOfView; + this->probeFieldOfView = config.probeFieldOfView; + this->virtualOriginalZ = config.virtualOriginalZ; + this->bMinScanAx = config.bMinScanAx; + this->bMinScanAz = config.bMinScanAz; + this->bMaxScanAx = config.bMaxScanAx; + this->bMaxScanAz = config.bMaxScanAz; + this->minScanAx = config.minScanAx; + this->minScanAz = config.minScanAz; + this->maxScanAx = config.maxScanAx; + this->steering = config.steering; + this->rxLineNo = config.rxLineNo; + this->rxFocusPointNo = config.rxFocusPointNo; + this->rxLineDaz = config.rxLineDaz; + this->rxPointDax = config.rxPointDax; + this->virtualConvex = config.virtualConvex; + this->vcMaxTheta = config.vcMaxTheta; + this->angle = config.angle; + this->pixel = config.pixel; + } + + BipScanConversionConfig_t() + { + this->linear = 0; + this->probeRadius = 0; + this->fieldOfView = 0; + this->probeFieldOfView = 0; + this->virtualOriginalZ = 0; + this->bMinScanAx = 0; + this->bMinScanAz = 0; + this->bMaxScanAx = 0; + this->bMaxScanAz = 0; + this->minScanAx = 0; + this->minScanAz = 0; + this->maxScanAx = 0; + this->steering = 0; + this->rxLineNo = 0; + this->rxFocusPointNo = 0; + this->rxLineDaz = 0; + this->rxPointDax = 0; + this->virtualConvex = 0; + this->vcMaxTheta = 0; + this->angle = 0; + } +}; + +#endif //BIPSCANCONVERSIONCONFIG_H diff --git a/include/model/backendImageProcessor/dtoInternal/KernelInput.h b/include/model/backendImageProcessor/dtoInternal/KernelInput.h new file mode 100644 index 0000000..646f5da --- /dev/null +++ b/include/model/backendImageProcessor/dtoInternal/KernelInput.h @@ -0,0 +1,55 @@ +#ifndef KERNELINPUT_H +#define KERNELINPUT_H + +#include + +#include "model/backendImageProcessor/dto/BipProbeProperties.h" +#include "model/backendImageProcessor/dtoInternal/BipScanConversionConfig.h" +#include "model/databaseManager/type/EAlgorithmType.h" + +typedef struct KernelInput_t +{ + //scan conversion + QList scanConvConfig; + quint64 outputWidth; + quint64 outputHeight; + //reject + int rejectBThreshold; + int rejectMThreshold; + //enhance + int enhanceBSelector; + int enhanceMSelector; + EAlgorithmType::eEnhanceAlgorithmType enhanceAlgorithm; + int enhanceLoGFilterSize; + QList enhanceAlpha; + QList enhanceSigma; + //dynamic contrast + int compressionType; + int dynamicContrastBGain; + int dynamicContrastMGain; + int dynamicContrastBSelector; + int dynamicContrastMSelector; + QList dynamicContrastGamma; + //sri + int sriSelector; + EAlgorithmType::eSriAlgorithmType sriAlgorithm; + QList sriAlpha; + QList sriWindowSize; + //cri + int cri; + int criFilterMode; + QList criFilterZeroSteeringWeight; + //grayMap + QList grayMapMList; + QList grayMapBList; + //tintmap + QList > tintMapMList; + QList > tintMapBList; + bool tintMapMEnable; + //persist + int persist; + //frame filter + int frameFilterMode; +}KernelInput_t; + +#endif //KERNELINPUT_H diff --git a/include/model/backendImageProcessor/type/EImageMode.h b/include/model/backendImageProcessor/type/EImageMode.h new file mode 100644 index 0000000..b4bfedd --- /dev/null +++ b/include/model/backendImageProcessor/type/EImageMode.h @@ -0,0 +1,92 @@ +#ifndef EIMAGEMODE_H +#define EIMAGEMODE_H + +#include + +/*************************************************************************************************/ +/** + * @brief The EImageMode enumeration class + * @author Mohsen Emami + * @date 14 Oct 2019 + */ +/*************************************************************************************************/ +class EImageMode : public QObject +{ + Q_OBJECT + +private: + //Private constructor prevent the enumeration class from being instantiated + explicit EImageMode(QObject* parent = nullptr); + +public: +/*************************************************************************************************/ +/** + * @brief Image Mode Enumerator + * + * Contains the reference enumerator for + * identificaiton of image modes. + */ +/*************************************************************************************************/ + enum eImageMode : quint8 + { + B, + BM, + BCri, + CineB, + CineBM, + CineBCri, + Test + }; + + Q_ENUM(eImageMode) + +/*************************************************************************************************/ +/** + * @brief enum to string converter + * @param qtEnum Enumerator to be converted to the relevant string + * @return String relevant to the input eImageMode enumerator + */ +/*************************************************************************************************/ + static QString qtEnumToQString(const eImageMode qtEnum) + { + return QVariant::fromValue(qtEnum).toString(); + } + +/*************************************************************************************************/ +/** + * @brief string to enum converter + * @param qtEnum Enumerator to be converted to the relevant string + * @return String relevant to the input eImageMode enumerator + */ +/*************************************************************************************************/ + static eImageMode qtQStringToEnum(const QString qtEnum) + { + return QVariant(qtEnum).value(); + } + +/*************************************************************************************************/ +/** + * @brief enum to value converter + * @param qtEnum Enumerator to be converted to the relevant value + * @return Identification value relevant to the input eImageMode enumerator + */ +/*************************************************************************************************/ + static int qtEnumToInt(const eImageMode qtEnum) + { + return QMetaEnum::fromType().value(qtEnum); + } + +/*************************************************************************************************/ +/** + * @brief int to enaum value converter + * @param int Enumerator to be converted to the relevant value + * @return int value relevant to the input eImageMode enumerator + */ +/*************************************************************************************************/ + static eImageMode intToEnum(const quint8 intEnum) + { + return static_cast(intEnum); + } +}; + +#endif //EIMAGEMODE_H diff --git a/include/model/backendImageProcessor/utils/KernelInputFetcher.h b/include/model/backendImageProcessor/utils/KernelInputFetcher.h new file mode 100644 index 0000000..8caf006 --- /dev/null +++ b/include/model/backendImageProcessor/utils/KernelInputFetcher.h @@ -0,0 +1,80 @@ +#ifndef KERNELINPUTFETCHER_H +#define KERNELINPUTFETCHER_H + +#include + +#include "model/backendImageProcessor/dtoInternal/BipInput.h" +#include "model/backendImageProcessor/dtoInternal/KernelInput.h" +#include "model/databaseManager/type/EDatabaseRequest.h" + +class KernelInputFetcher : public QObject +{ + Q_OBJECT + +private: + KernelInput_t _kernelInput; + BipInput_t _bipInput; + + bool _success; + QList _valueList; + + void getKernelsConstantData(); + void getKernelsInputRelatedData(BipInput_t input); + + void updateGrayMapBParameters(BipInput_t input); + void updateGrayMapMParameters(BipInput_t input); + + void updateTintMapBParameters(BipInput_t input); + bool tintMapBSelectorHasChanged(BipInput_t input); + + void updateTintMapMParameters(BipInput_t input); + bool tintMapMSelectorHasChanged(BipInput_t input); + + void updateDynamicContrastBParameters(BipInput_t input); + void updateDynamicContrastMParameters(BipInput_t input); + + void updateEnhanceBParameters(BipInput_t input); + void updateEnhanceMParameters(BipInput_t input); + + void updateRejectBParameters(BipInput_t input); + void updateRejectMParameters(BipInput_t input); + + void updateSriParameters(BipInput_t input); + + void updatePersistParameters(BipInput_t input); + void updateFrameFilterParameters(BipInput_t input); + + void updateScanConvParameters(BipInput_t input); + + void updateCriParameters(BipInput_t input); + + void updateImageSizeParameters(BipInput_t input); + + void getSriAlgorithmConstantData(); + QList getGrayMapAlgorithmData(int grayMapSelector); + QList > getTintMapAlgorithmData(int tintMapSelector); + void getEnhanceAlgorithmConstantData(); + void getCriFilterAlgorithmConstantData(); + void getDynamicContrastAlgorithmConstantData(); + + void getSysParamsData(); + + template + T translateDatabaseData(const QList result); + +public: + KernelInputFetcher(); + + void newBipInput(BipInput_t input); + KernelInput_t getKernelInput(); + + void init(); + + void setRequestResult(bool success, QList valueList); + +signals: + void requestDataFromDatabase(EDatabaseRequest::eDatabaseRequest request, + const QList args); +}; + +#endif //KERNELINPUTFETCHER_H diff --git a/include/model/backendImageProcessor/utils/OpenClHelper.h b/include/model/backendImageProcessor/utils/OpenClHelper.h new file mode 100644 index 0000000..d8083d2 --- /dev/null +++ b/include/model/backendImageProcessor/utils/OpenClHelper.h @@ -0,0 +1,654 @@ +#ifndef OPENCLHELPER_H +#define OPENCLHELPER_H + +#define CL_HPP_MINIMUM_OPENCL_VERSION 120 +#define CL_HPP_TARGET_OPENCL_VERSION 120 + +#include +#include + +#include "logger/Logger.h" +#include "lib/CL/cl2.hpp" + +#define caseReturnString(x) case x: \ + return #x + +/*************************************************************************************************/ +/** + * @brief The OpenCLHelper class + * @note This class can not be broken to .h and .cpp files, because of the way opencl works, + * if we include it in 2 places it complains about duplicated defenition + * @author Mohsen Emami revised by Hessamoddin Hediyehloo(H-4nd-H) + * @date 2019/8/5(1398/5/14) + */ +/*************************************************************************************************/ +class OpenClHelper : public QObject +{ + Q_OBJECT + +private: + inline std::vector getAllAvailablePlatform(); + + inline std::vector getAmdAndNvidiaPlatforms(); + + inline std::vector filterNoneAmdAndNoneNvidiaPlatforms( + std::vector platforms); + + inline void ThrowIfNoPlatformAvailable(const std::vector& platforms); + + inline std::vector getAllAvailableDevicesForValidPlatforms( + const std::vector& platforms); + + inline std::vector getAllAvailableDevicesForGivenPlatforms( + const cl::Platform& platform); + + inline void ThrowIfNoDeviceAvailable(const std::vector& devices); + + inline QString getErrorString(int error); + + inline QString getKernelFullPath(QString kernelPath, QString kernelName); + + inline std::string readKernelSourceCode(QString kernelPath); + + inline cl::Program createProgramFromKernelCode(const cl::Context& context, + std::string kernelSource); + + inline cl::Kernel createKernelFromProgram(const cl::Program& program, QString kernelName); + +public: + inline cl::Context& getContext(); + inline cl::Device getFirstDeviceByContext(const cl::Context& context); + inline cl::Kernel createKernel(const cl::Context& context, + const QString kernelPath, + const QString KernelName); + + inline cl::Buffer* allocateClBuffer(const cl::Context& context, + quint64 size, + bool read); + + inline cl::Image* allocateClImage(const cl::Context& context, + cl::ImageFormat clFrameFormat, + QList dimensions, bool read); + + inline cl::CommandQueue createCommandQueue(const cl::Context& context, + const cl_command_queue_properties properties); + template + inline cl::KernelFunctor createKernelFunctor(const cl::Kernel& kernel); + + template + inline void runKernelFunctor(cl::KernelFunctor& kernelFunctor, + cl::EnqueueArgs args, + Ts... ts); +}; + +/*************************************************************************************************/ +/** + * @brief Returns the name of error + * @param error The error to get th ename of + * @return The error name + */ +/*************************************************************************************************/ +QString OpenClHelper::getErrorString(int error) +{ + switch(error) + { + caseReturnString(CL_SUCCESS); + caseReturnString(CL_DEVICE_NOT_FOUND); + caseReturnString(CL_DEVICE_NOT_AVAILABLE); + caseReturnString(CL_COMPILER_NOT_AVAILABLE); + caseReturnString(CL_MEM_OBJECT_ALLOCATION_FAILURE); + caseReturnString(CL_OUT_OF_RESOURCES); + caseReturnString(CL_OUT_OF_HOST_MEMORY); + caseReturnString(CL_PROFILING_INFO_NOT_AVAILABLE); + caseReturnString(CL_MEM_COPY_OVERLAP); + caseReturnString(CL_IMAGE_FORMAT_MISMATCH); + caseReturnString(CL_IMAGE_FORMAT_NOT_SUPPORTED); + caseReturnString(CL_BUILD_PROGRAM_FAILURE); + caseReturnString(CL_MAP_FAILURE); + caseReturnString(CL_MISALIGNED_SUB_BUFFER_OFFSET); + caseReturnString(CL_COMPILE_PROGRAM_FAILURE); + caseReturnString(CL_LINKER_NOT_AVAILABLE); + caseReturnString(CL_LINK_PROGRAM_FAILURE); + caseReturnString(CL_DEVICE_PARTITION_FAILED); + caseReturnString(CL_KERNEL_ARG_INFO_NOT_AVAILABLE); + caseReturnString(CL_INVALID_VALUE); + caseReturnString(CL_INVALID_DEVICE_TYPE); + caseReturnString(CL_INVALID_PLATFORM); + caseReturnString(CL_INVALID_DEVICE); + caseReturnString(CL_INVALID_CONTEXT); + caseReturnString(CL_INVALID_QUEUE_PROPERTIES); + caseReturnString(CL_INVALID_COMMAND_QUEUE); + caseReturnString(CL_INVALID_HOST_PTR); + caseReturnString(CL_INVALID_MEM_OBJECT); + caseReturnString(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR); + caseReturnString(CL_INVALID_IMAGE_SIZE); + caseReturnString(CL_INVALID_SAMPLER); + caseReturnString(CL_INVALID_BINARY); + caseReturnString(CL_INVALID_BUILD_OPTIONS); + caseReturnString(CL_INVALID_PROGRAM); + caseReturnString(CL_INVALID_PROGRAM_EXECUTABLE); + caseReturnString(CL_INVALID_KERNEL_NAME); + caseReturnString(CL_INVALID_KERNEL_DEFINITION); + caseReturnString(CL_INVALID_KERNEL); + caseReturnString(CL_INVALID_ARG_INDEX); + caseReturnString(CL_INVALID_ARG_VALUE); + caseReturnString(CL_INVALID_ARG_SIZE); + caseReturnString(CL_INVALID_KERNEL_ARGS); + caseReturnString(CL_INVALID_WORK_DIMENSION); + caseReturnString(CL_INVALID_WORK_GROUP_SIZE); + caseReturnString(CL_INVALID_WORK_ITEM_SIZE); + caseReturnString(CL_INVALID_GLOBAL_OFFSET); + caseReturnString(CL_INVALID_EVENT_WAIT_LIST); + caseReturnString(CL_INVALID_EVENT); + caseReturnString(CL_INVALID_OPERATION); + caseReturnString(CL_INVALID_GL_OBJECT); + caseReturnString(CL_INVALID_BUFFER_SIZE); + caseReturnString(CL_INVALID_MIP_LEVEL); + caseReturnString(CL_INVALID_GLOBAL_WORK_SIZE); + caseReturnString(CL_INVALID_PROPERTY); + caseReturnString(CL_INVALID_IMAGE_DESCRIPTOR); + caseReturnString(CL_INVALID_COMPILER_OPTIONS); + caseReturnString(CL_INVALID_LINKER_OPTIONS); + caseReturnString(CL_INVALID_DEVICE_PARTITION_COUNT); + + default: + return "Unknown OpenCL error code"; + } +} + +/*************************************************************************************************/ +/** + * @brief Return the full file path for the kernel + * @param kernelPath Directory of kernel + * @param kernelName Kernel name + * @return Full kernel path + */ +/*************************************************************************************************/ +QString OpenClHelper::getKernelFullPath(QString kernelPath, QString kernelName) +{ + return QDir(kernelPath).filePath(kernelName + ".cl"); +} + +/*************************************************************************************************/ +/** + * @brief Read kernel source file from the given path + * @param kernelPath Kernel file path + * @return Kernel source code + */ +/*************************************************************************************************/ +std::string OpenClHelper::readKernelSourceCode(QString kernelPath) +{ + QFile kernelFile(kernelPath); + + if(!kernelFile.open(QIODevice::ReadOnly | QIODevice::Text)) + { + throw LoggerException(ESeverityLevel::Alert, + ELogID::CLKernelError, + "Can not open kernel file @ " + kernelPath, + this->metaObject()->className()); + } + + auto kernelSource = kernelFile.readAll().toStdString(); + + kernelFile.close(); + + return kernelSource; +} + +/*************************************************************************************************/ +/** + * @brief Compile the rkernel code and create a ne wprogram object + * @param context OpenCL object + * @param kernelSource Kernel source code + * @return Created program object + */ +/*************************************************************************************************/ +cl::Program OpenClHelper::createProgramFromKernelCode(const cl::Context& context, + std::string kernelSource) +{ + cl_int err = 0; + + cl::Program program(context, kernelSource, true, &err); + + if(err != CL_SUCCESS) + { + throw LoggerException(ESeverityLevel::Alert, + ELogID::CLKernelError, + getErrorString(err), + this->metaObject()->className()); + } + + return program; +} + +/*************************************************************************************************/ +/** + * @brief Create kernel object from openCl program object + * @param program OpenCL program object + * @param kernelName Name of the kernel + * @return OpenCl kernel + */ +/*************************************************************************************************/ +cl::Kernel OpenClHelper::createKernelFromProgram(const cl::Program& program, QString kernelName) +{ + cl_int err; + + cl::Kernel kernel(program, kernelName.toStdString().c_str(), &err); + + if(err != CL_SUCCESS) + { + throw LoggerException(ESeverityLevel::Alert, + ELogID::CLKernelError, + getErrorString(err), + this->metaObject()->className()); + } + + return kernel; +} + +/*************************************************************************************************/ +/** + * @brief Checks to see if platform list is empty or not, throws exception if empty + * @param platforms List of platforms + */ +/*************************************************************************************************/ +void OpenClHelper::ThrowIfNoPlatformAvailable(const std::vector& platforms) +{ + if(platforms.size() > 0) + { + return; + } + + throw LoggerException(ESeverityLevel::Alert, + ELogID::CLPlatformError, + "No valid platform was found", + this->metaObject()->className()); +} + +/*************************************************************************************************/ +/** + * @brief Checks to see if device list is empty or not, throws exception if empty + * @param devices List of devices + */ +/*************************************************************************************************/ +void OpenClHelper::ThrowIfNoDeviceAvailable(const std::vector& devices) +{ + if(devices.size() > 0) + { + return; + } + + throw LoggerException(ESeverityLevel::Alert, + ELogID::CLDeviceError, + "No valid device was found", + this->metaObject()->className()); +} + +/*************************************************************************************************/ +/** + * @brief Return all available opencl platforms + * @return Availaable opencl platforms + */ +/*************************************************************************************************/ +std::vector OpenClHelper::getAllAvailablePlatform() +{ + std::vector availablePlatforms; + + cl_int err = cl::Platform::get(&availablePlatforms); + if(err != CL_SUCCESS) + { + throw LoggerException(ESeverityLevel::Alert, + ELogID::CLPlatformError, + getErrorString(err), + this->metaObject()->className()); + } + + return availablePlatforms; +} + +/*************************************************************************************************/ +/** + * @brief Remove none amd and none nvidia paltforsm from a given list of platforms + * @param platforms List of available platforms + * @return Platform list containing only nvidia and amd + */ +/*************************************************************************************************/ +std::vector OpenClHelper::filterNoneAmdAndNoneNvidiaPlatforms( + std::vector platforms) +{ + std::vector AmdNvidiaPlatforms; + for(auto it = platforms.begin(); it != platforms.end(); it++) + { + cl::string currentPlatformName = it->getInfo(); + + Logger::log(ESeverityLevel::Debug, ELogID::CLPlatformInfo, + "Platform Name: " + QString::fromStdString(currentPlatformName), + this->metaObject()->className()); + + if(!(it->getInfo().find("NVIDIA") == cl::string::npos) || + !(it->getInfo().find("AMD") == cl::string::npos)) + { + AmdNvidiaPlatforms.push_back(*it); + } + } + + return AmdNvidiaPlatforms; +} + +/*************************************************************************************************/ +/** + * @brief gets available nvidia or amd platforms on host machine + * @return platforms The list of available nvidia nd amd platforms + */ +/*************************************************************************************************/ +std::vector OpenClHelper::getAmdAndNvidiaPlatforms() +{ + auto availablePlatform = getAllAvailablePlatform(); + + availablePlatform = filterNoneAmdAndNoneNvidiaPlatforms(availablePlatform); + + ThrowIfNoPlatformAvailable(availablePlatform); + + return availablePlatform; +} + +/*************************************************************************************************/ +/** + * @brief get the opencl devices for all provided platforms + * @param platforms The list of nvidia and amd platforms \sa getPlatforms + * @return devices List of available devices for provided platforms + */ +/*************************************************************************************************/ +std::vector OpenClHelper::getAllAvailableDevicesForValidPlatforms( + const std::vector& platforms) +{ + std::vector availableDevices; + for(auto platform = platforms.begin(); platform != platforms.end(); platform++) + { + auto temp = getAllAvailableDevicesForGivenPlatforms(*platform); + + for(auto device = temp.begin(); device != temp.end(); device++) + { + availableDevices.push_back(*device); + cl::string currentDeviceName = device->getInfo(); + + Logger::log(ESeverityLevel::Debug, ELogID::CLDeviceInfo, + "Device Name: " + QString::fromStdString(currentDeviceName), + this->metaObject()->className()); + } + } + + return availableDevices; +} + +std::vector OpenClHelper::getAllAvailableDevicesForGivenPlatforms( + const cl::Platform& platform) +{ + std::vector availableDevices; + cl_int err = platform.getDevices(CL_DEVICE_TYPE_GPU, &availableDevices); + + if(err != CL_SUCCESS) + { + throw LoggerException(ESeverityLevel::Alert, + ELogID::CLDeviceError, + getErrorString(err), + this->metaObject()->className()); + } + + return availableDevices; +} + +/*************************************************************************************************/ +/** + * @brief get context of opencl + * @return context Actual opencl context + */ +/*************************************************************************************************/ +cl::Context& OpenClHelper::getContext() +{ + static cl::Context* internalContext = nullptr; + if(internalContext) + { + return *internalContext; + } + + auto platforms = getAmdAndNvidiaPlatforms(); + + auto devices = getAllAvailableDevicesForValidPlatforms(platforms); + + cl_int err; + internalContext = new cl::Context(devices, Q_NULLPTR, Q_NULLPTR, Q_NULLPTR, &err); + + if(err != CL_SUCCESS) + { + throw LoggerException(ESeverityLevel::Alert, + ELogID::CLContextError, + getErrorString(err), + this->metaObject()->className()); + } + + return *internalContext; +} + +/*************************************************************************************************/ +/** + * @brief Creates and compiles the given kernel + * @param context OpenCl contex \sa getContext + * @param kernelPath The folder directory for kernel + * @param kernelName The kernel file name without .cl extension + * @return kernel The newly created kernel instance + */ +/*************************************************************************************************/ +cl::Kernel OpenClHelper::createKernel(const cl::Context& context, + const QString kernelPath, + const QString kernelName) +{ + auto kernelFullPath = getKernelFullPath(kernelPath, kernelName); + + auto kernelSource = readKernelSourceCode(kernelFullPath); + + auto program = createProgramFromKernelCode(context, kernelSource); + + return createKernelFromProgram(program, kernelName); +} + +/*************************************************************************************************/ +/** + * @brief allocate a cl buffer + * @param context OpenCL context \sa getContext + * @param size Number of bytes to allocate + * @param read Should the buffer be allocated with read access or write access + * @return buffer The allocated buffer pointer + */ +/*************************************************************************************************/ +cl::Buffer* OpenClHelper::allocateClBuffer(const cl::Context& context, + quint64 size, bool read = true) +{ + cl_mem_flags clMemFlags = read ? CL_MEM_READ_ONLY : CL_MEM_WRITE_ONLY; + + cl_int err; + auto buffer = new cl::Buffer(context, clMemFlags, size, Q_NULLPTR, &err); + if(err != CL_SUCCESS) + { + throw LoggerException(ESeverityLevel::Alert, + ELogID::CLBufferError, + getErrorString(err), + this->metaObject()->className()); + } + + return buffer; +} + +/*************************************************************************************************/ +/** + * @brief Allocate proper CL image based on input + * @param context OpenCL context \sa getContext + * @param clFrameFormat Frame format for image + * @param dimensions List containing size for each image dimension, can be 1D, 2D or 3D + * @return image Actual allocated image + */ +/*************************************************************************************************/ +cl::Image* OpenClHelper::allocateClImage(const cl::Context& context, + cl::ImageFormat clFrameFormat, + QList dimensions, + bool read) +{ + cl_mem_flags clMemFlags = CL_MEM_READ_WRITE; + + cl::Image* image = Q_NULLPTR; + + cl_int err = 0; + + switch(dimensions.size()) + { + case 1: + image = new cl::Image1D(context, + clMemFlags, + clFrameFormat, + dimensions[0], + &err); + break; + + case 2: + image = new cl::Image2D(context, + clMemFlags, + clFrameFormat, + dimensions[0], + dimensions[1], + 0, + &err); + break; + + case 3: + image = new cl::Image3D(context, + clMemFlags, + clFrameFormat, + dimensions[0], + dimensions[1], + dimensions[2], + 0, + 0, + &err); + break; + + default: + throw LoggerException(ESeverityLevel::Alert, + ELogID::CLFrameError, + "Invalid dimension size", + this->metaObject()->className()); + } + + if(err != CL_SUCCESS) + { + throw LoggerException(ESeverityLevel::Alert, + ELogID::CLFrameError, + getErrorString(err), + this->metaObject()->className()); + } + + return image; +} + +/*************************************************************************************************/ +/** + * @brief Creates a functor for given kernel + * @param kernel The kernel to build functor for + * @return functor The created functor + */ +/*************************************************************************************************/ +template +cl::KernelFunctor OpenClHelper::createKernelFunctor(const cl::Kernel& kernel) +{ + auto kernelName = QString::fromStdString(kernel.getInfo()); + + cl_int err; + + cl::KernelFunctor functor(kernel.getInfo(), kernelName, &err); + + if(err != CL_SUCCESS) + { + throw LoggerException(ESeverityLevel::Alert, + ELogID::CLKernelFunctorError, + getErrorString(err), + this->metaObject()->className()); + } + + return functor; +} + +/*************************************************************************************************/ +/** + * @brief Create an OpenCl commandQueue + * @param context OpenCL context \sa getContext + * @param properties Properties to build queue upon them + * @return queue The newly created queue + */ +/*************************************************************************************************/ +cl::CommandQueue OpenClHelper::createCommandQueue(const cl::Context& context, + const cl_command_queue_properties properties) +{ + cl_int err; + cl::CommandQueue commandQueue(context, properties, &err); + + if(err != CL_SUCCESS) + { + throw LoggerException(ESeverityLevel::Alert, + ELogID::CLCommandQueueCreationError, + getErrorString(err), + this->metaObject()->className()); + } + + return commandQueue; +} + +/*************************************************************************************************/ +/** + * @brief Returns the first device of context + * @param context OpenCl context \sa getContext + * @param device First device of context + * @return success or failure + */ +/*************************************************************************************************/ +cl::Device OpenClHelper::getFirstDeviceByContext(const cl::Context& context) +{ + std::vector devices; + auto err = context.getInfo >(CL_CONTEXT_DEVICES, &devices); + + if(err != CL_SUCCESS) + { + throw LoggerException(ESeverityLevel::Alert, + ELogID::CLDeviceError, + getErrorString(err), + this->metaObject()->className()); + } + + return devices[0]; +} + +/*************************************************************************************************/ +/** + * @brief Run the kernel functor \sa createKernelFunctor + * @param kernelFunctor Functor to run + * @param args Arg structure for functor + * @param ts actual arg for functor + * @return success or failure + */ +/*************************************************************************************************/ +template +void OpenClHelper::runKernelFunctor(cl::KernelFunctor& kernelFunctor, + cl::EnqueueArgs args, + Ts... ts) +{ + cl_int err; + kernelFunctor(args, ts ..., err); + + if(err != CL_SUCCESS) + { + throw LoggerException(ESeverityLevel::Alert, + ELogID::CLKernelRunError, + getErrorString(err), + this->metaObject()->className()); + } +} + +#endif diff --git a/include/model/bipTester/BipTester.h b/include/model/bipTester/BipTester.h new file mode 100644 index 0000000..36ee41d --- /dev/null +++ b/include/model/bipTester/BipTester.h @@ -0,0 +1,38 @@ +#ifndef BIPTESTER_H +#define BIPTESTER_H + +#include +#include +#include + +#include "model/ultrasoundModule/UsModule.h" +#include "core/BipTesterCore.h" + +class BipTester : public UsModule +{ + Q_OBJECT + US_MODULE + +private: + static BipTester* _instance; + static QMutex _mutex; + + bool _run; + + BipTesterCore* _core; + + BipTester(); + ~BipTester() override; + +public: + static BipTester* getInstance(); + +//uncrustify off +public slots: +//uncrustify on + void dataReady(const UsPacket& data); + void paramsReady(QVariant output); + void newSimulationState(bool run); +}; + +#endif //BIPTESTER_H diff --git a/include/model/bipTester/core/BipTesterCore.h b/include/model/bipTester/core/BipTesterCore.h new file mode 100644 index 0000000..3258f9d --- /dev/null +++ b/include/model/bipTester/core/BipTesterCore.h @@ -0,0 +1,105 @@ +#ifndef CORE_H +#define CORE_H + +#include +#include + +#include "model/scenarioGenerator/dto/software/SoftwareOutput.h" +#include "model/ultrasoundModule/UsPacket.h" +#include "model/bipTester/core/BipTesterMetadata.h" +#include "model/hardware/service/HardwarePacketEngine.h" + +#define HEX2FLT(x) *(reinterpret_cast(&x)) + +#define PARSE toUInt(Q_NULLPTR, 16) + +#define READ_INP2(NAME) \ + if(sl[0] == #NAME) \ + { \ + auto temp = sl[1].PARSE; \ + _output.NAME = HEX2FLT(temp); \ + } + +#define READ_INP(NAME) \ + if(sl[0] == #NAME) \ + { \ + auto temp = sl[1].PARSE; \ + _output.NAME = HEX2FLT(temp); \ + } + +#define READ_INP_BOOL(NAME) \ + if(sl[0] == #NAME) \ + { \ + auto temp = sl[1].PARSE; \ + _output.NAME = HEX2FLT(temp) == 1; \ + } + +typedef struct input_t { + QString workingDir; +}input_t; + +typedef struct simState_t { + quint32 currentScenarioNumber; + bool rxTesterMode; + bool oneshot; + bool autoIncrement; + quint32 maxFileNumber; + quint32 maxCriNumber; + quint32 maxPersistNumber; +}simState_t; + +class BipTesterCore : public QObject +{ + Q_OBJECT + +private: + input_t _input; + simState_t _simState; + ScenGenSoftwareOutput_t _output; + + bool _run; + int _frameCounter; + + QList _cri = {1, 3, 3, 3, 3, 5, 7, 9, 11}; + + void loadParams(); + + QString makeInputFolderPath(); + QString makeOutputFolderPath(); + QString makeParamsFolderPath(); + QString makeFileNameString(); + QString makeFileNameString(int scenNum); + QString makeFileNameString(int scenNum, int persist, int cri); + + HardwarePacketEngine _engine; + +public: + BipTesterCore(); + + QList > grayMap; + + void changeWorkingDir(QString path); + void changeMode(bool rxMode); + void changeOneshot(bool oneshot); + void changeAutoInc(bool autoInc); + + void start(); + void stop(); + + void feedData(); + void flowManager(); + void frameProcessed(const UsPacket& packet); + +signals: + void newParams(QVariant params); + void newData(const UsPacket& packet); + void simulationChanged(bool run); + void quit(); + +//uncrustify off +public slots: +//uncrustify on + void newPacket(const UsPacket& packet); +}; + +#endif //CORE_H diff --git a/include/model/bipTester/core/BipTesterMetadata.h b/include/model/bipTester/core/BipTesterMetadata.h new file mode 100644 index 0000000..21601ff --- /dev/null +++ b/include/model/bipTester/core/BipTesterMetadata.h @@ -0,0 +1,21 @@ +#ifndef BIPTESTERMETADAYA_H +#define BIPTESTERMETADAYA_H + +#include + +#include "model/ultrasoundModule/metadata/UsBaseMetadata.h" + +class BipTesterMetadata : public UsBaseMetadata +{ +public: + bool isLast; + int persist; + int cri; + int scenNum; + QString logPath; + BipTesterMetadata(); +}; + +Q_DECLARE_METATYPE(BipTesterMetadata) + +#endif //BIPTESTERMETADAYA_H diff --git a/include/model/bipTester/utils/FileHelper.h b/include/model/bipTester/utils/FileHelper.h new file mode 100644 index 0000000..cb05574 --- /dev/null +++ b/include/model/bipTester/utils/FileHelper.h @@ -0,0 +1,19 @@ +#ifndef FILE_HELPER_H +#define FILE_HELPER_H + +#include +#include + +class FileHelper +{ +public: + FileHelper() + { + } + + static bool ReadInputFile(QByteArray& arr, QString path, quint64* width, quint64* height); + static bool ReadInputFile(QByteArray& arr, QString path); + static bool WriteOutputFile(char* arr, QString path, quint64 width, quint64 height); +}; + +#endif //FILE_HELPER_H diff --git a/include/model/csm/Csm.h b/include/model/csm/Csm.h new file mode 100644 index 0000000..b0e4234 --- /dev/null +++ b/include/model/csm/Csm.h @@ -0,0 +1,44 @@ +#ifndef CSM_H +#define CSM_H + +#include +#include +#include +#include + +#include "model/ultrasoundModule/UsModule.h" +#include "viewModel/factory/ApplicationStarter.h" +#include "model/csm/core/ConsoleCore.h" +#include "model/scenarioGenerator/ScenarioGenerator.h" +#include "model/ultrasoundModule/UsHelper.h" +#include "model/csm/dto/TrackballConfig.h" + +class Csm : public UsModule +{ + Q_OBJECT + US_MODULE + +private: + static Csm* _instance; + static QMutex _mutex; + + ConsoleCore* _consoleCore; + TrackballCore* _trackballCore; + + Csm(); + ~Csm() override; + + int mCursorX; + int mCursorY; + +public: + static Csm* getInstance(); + +//uncrustify off +public slots: +//uncrustify on + void recieveCommandFromCore(const CommandControl_t command); + void recieveTrackballConfigFromCore(TrackballConfig_t config); +}; + +#endif //CSM_H diff --git a/include/model/csm/core/ConsoleCore.h b/include/model/csm/core/ConsoleCore.h new file mode 100644 index 0000000..54d5f81 --- /dev/null +++ b/include/model/csm/core/ConsoleCore.h @@ -0,0 +1,78 @@ + #ifndef CSMCORE_H +#define CSMCORE_H + +#include +#include +#include + +#include "model/csm/utils/XmlConsoleConfigReader.h" +#include "model/csm/utils/XmlGraphStateReader.h" +#include "model/csm/core/consoleComponent/ConsoleButton.h" +//#include "model/csm/dto/CommandTuple.h" +#include "config/Configuration.h" +#include "model/csm/core/Hid.h" + +/*****************************************************************************/ +/** + * @brief this is the core of console management system. this class mange aonsole and trackball as + * a part of user interface. + * @author Mohammad Mohsen Talaie + * @details + * @date 12 jan 20214 + */ +/*****************************************************************************/ +class ConsoleCore : public QObject +{ + Q_OBJECT + +private: + QString _configPath; + QList _btnList; + QString _probType; + + EConsole::eConsoleState _currentState; + XmlConsoleConfigReader* _consoleConfigReader; + XmlGraphStateReader* _graphStateReader; + Graph _consoleStateGraph; + + Hid* _hidHandler; + + Graph getConsoleStateGraph() const; + + void readConfigFile(); + void setConsoleStateGraph(const Graph& csmStateGraph); + void connectToConsoleButton(const ConsoleButton* consoleButton); + + void checkMicro(); + void blink(); + +public: + ConsoleCore(); + + void setCurrentConsoleState(const EConsole::eConsoleState& csmState, const QString& probType); + + void init(); + void newInterrupt(const EConsole::eCsmInterruptType& interrupt, const QString& value); + + void setProbType(const QString& prbType); + QString getProbType() const; + + EConsole::eConsoleState getCurrentState() const; + + void selfTest(); + +signals: + void sendChangeStateToButton(const EConsole::eConsoleState& csmState, const QString& probType); + void sendCommandToCsmModule(const CommandControl_t& commands); + void sendInterruptToTrackball(const EConsole::eCsmInterruptType& interrupt, + const QString& value); +//uncrustify off +public slots: +//uncrustify on + void recieveButtonCommand(const QList& commands, + const quint8& fCode); + void recieveButtonLongPressCommand(const QList& commands, + const quint8& fCode); +}; + +#endif //CSMCORE_H diff --git a/include/model/csm/core/EMenuTab.h b/include/model/csm/core/EMenuTab.h new file mode 100644 index 0000000..4ad862c --- /dev/null +++ b/include/model/csm/core/EMenuTab.h @@ -0,0 +1,43 @@ +#ifndef EMENUTAB_H +#define EMENUTAB_H + +#include +#include + +class EMenuTab : public QObject +{ + Q_OBJECT + +private: + //Private constructor prevent the enumeration class from being instantiated + explicit EMenuTab(QObject* parent = nullptr); + +public: + enum eMenuTab : quint8 + { + EMPTY_TAB, + B_TAB, + M_TAB, + C_TAB, + PW_TAB, + PD_TAB, + CINE_TAB, + TGC_TAB + }; + + Q_ENUM(eMenuTab) + + static int qtEnumToInt(const eMenuTab qtEnum) + { + return QMetaEnum::fromType().value(qtEnum); + } + + static QString qtEnumToString(const eMenuTab qtEnum) + { + return QString(QMetaEnum::fromType().valueToKey(qtEnum)); + } +}; + +Q_DECLARE_METATYPE(EMenuTab::eMenuTab); + +#endif //EMENUTAB_H diff --git a/include/model/csm/core/Hid.h b/include/model/csm/core/Hid.h new file mode 100644 index 0000000..fc36482 --- /dev/null +++ b/include/model/csm/core/Hid.h @@ -0,0 +1,79 @@ +#ifndef HID_H +#define HID_H + +#include +#include +#include +#include + +#include "model/ultrasoundModule/UsHelper.h" +#include "model/csm/core/consoleComponent/ConsoleButton.h" +#include "model/ultrasoundModule/type/ECommandType.h" +#include "model/csm/core/TrackballCore.h" +#include "model/csm/dto/HidPacket.h" +#include "hidapi/hidapi.h" + +class SglContainer : public QObject +{ + Q_OBJECT + +signals: + void sendHitButton(HidPacket_t); +}; + +class TrackballCore; + +/*****************************************************************************/ +/** + * @brief this is a handler for hid interface. + * @author Mohammad Mohsen Talaie + * @details + * @date 21 sep 2020 + */ +/*****************************************************************************/ +class Hid : public QObject +{ + Q_OBJECT + SINGLETON(Hid) + +private: + Hid(); + QFuture readThreadFuture; + QFuture writeThreadFuture; + QFuture processThreadFuture; + void readThread(); + void writeThread(); + void processThread(); + + QList _readFifo; + QMutex _readFifoLocker; + + QList _writeFifo; + QMutex _writeFifoLocker; + + QMutex _readHidLocker; + + QMap _signalFuctionCodeTable; + + bool _run = true; + + hid_device* _handle; + +public: + ~Hid(); + void start(); + void initConsoleButtons(const QList& consoleButtons); + void initTracballButtons(const QList& trackballButtons); + + bool exist(); + bool sendEcho(); + bool turnOnAllLeds(); + bool turnOffAllLeds(); + +//uncrustify off +public slots: +//uncrustify on + void recieveLedStatus(const QMap& ledStatus); +}; + +#endif //HID_H diff --git a/include/model/csm/core/TrackballCore.h b/include/model/csm/core/TrackballCore.h new file mode 100644 index 0000000..8b6044a --- /dev/null +++ b/include/model/csm/core/TrackballCore.h @@ -0,0 +1,125 @@ +#ifndef TRACKBALLCORE_H +#define TRACKBALLCORE_H + +#include +#include +#include +#include +#include +#include + +#include "model/csm/utils/XmlGraphStateReader.h" +#include "model/csm/utils/XmlTrackballConfigReader.h" +#include "model/csm/core/trackballComponent/HidButton.h" +#include "model/csm/core/trackballComponent/MiceButton.h" +#include "model/csm/core/trackballComponent/CenterBall.h" +#include "model/csm/dto/TrackballConfig.h" +#include "model/csm/type/EConsole.h" +#include "config/Configuration.h" +#include "model/csm/dto/HidPacket.h" +#include "model/ultrasoundModule/UsHelper.h" +#include "model/csm/core/Hid.h" + +class Hid; + +class TrackballCore : public QObject +{ + Q_OBJECT + SINGLETON(TrackballCore) + +private: + Hid* _hidHandler; + XmlGraphStateReader* _graphStateReader; + XmlTrackballConfigReader* _trackballConfigReader; + + QString _configPath; + TrackballConfig_t _currentConfig; + + //mice button + MiceButton* _middleTop; + MiceButton* _left; + MiceButton* _right; + + //hid button + HidButton* _topLeft; + HidButton* _topRight; + HidButton* _bottomLeft; + HidButton* _bottomRight; + HidButton* _middleBottom; + + //center ball + CenterBall* _centerBall; + + QMap hidFucitonMap; + + //state + EConsole::eTrackballState _currentState; + + //mode + EConsole::eTrackballMode _currentMode; + + //Pointer temp Memory + QPoint _pointerMemory; + + QPoint _currentTrackballPos; + QPoint _trackballPosTemp; + QPoint _trackballPosDifference; + + Graph _trackballStateGraph; + + TrackballCore(); + + void sendCommandForMicePushButton(MiceButton* miceButton, const QMouseEvent* mouseEvent); + + void trackballModeMiceEventHandler(QEvent* ev); + + void mouseModeEventHandler(QEvent* ev); + + void trackballMoveEventHandler(QEvent* ev); + + void miceButtonPushHandler(MiceButton* miceButton, + const QMouseEvent* mouseEvent, + const QString interruptValue); + + void newInterrupt(EConsole::eCsmInterruptType interrupt, QString value); + + void readConfigFile(); + + void changeMiceToTrackball(); + + void changeMiceToMouse(); + + QPoint getCursorPosiotion(); + +protected: + bool event(QEvent*) override; + +public: +//virtual bool eventFilter(QObject* object, QEvent* ev) override; + + void init(); + + TrackballConfig_t getCurrentConfig(); + + void loadConfig(const EConsole::eTrackballState tracballState); + void refreshAndSendConfig(); + void clearConfig(); + void configFiller(const EConsole::eTrackballItem item, + const QString text, + const bool enable = true, + const bool active = true); + void setTrackballState(EConsole::eTrackballState state); + void swapMode(); + +signals: + void sendConfigToCsmModule(TrackballConfig_t config); + void sendCommandToCsmModule(CommandControl_t command); +//uncrustify off +public slots: +//uncrustify on + void reciveEvents(QMouseEvent* ev); + void recievePush(HidPacket_t data); + void recieveChangeTrackballState(EConsole::eCsmInterruptType interruptType, QString value); +}; + +#endif //TRACKBALLCORE_H diff --git a/include/model/csm/core/consoleComponent/Button.h b/include/model/csm/core/consoleComponent/Button.h new file mode 100644 index 0000000..0cb7df0 --- /dev/null +++ b/include/model/csm/core/consoleComponent/Button.h @@ -0,0 +1,63 @@ +#ifndef BUTTON_H +#define BUTTON_H + +#include +#include +#include + +#include "model/csm/core/consoleComponent/ControlAbstract.h" + +/*****************************************************************************/ +/** + * @brief Button Class, this class is a part of console button + * @author Mohammad Mohsen Talaie + * @details + * @date 12 Jan 2021 + */ +/*****************************************************************************/ +class Button : public ControlAbstract +{ +private: + bool _down; + QMutex _downLoker; + QElapsedTimer _timer; + + QList _currentCommandList; + QList _longPressCommands; + QList _commonLongPressCommands; + QMap > _longPressCommandListBasedOnState; + + bool _longPressEnable; + +public: + Button() + { + } + + QList getCommandList(const EConsole::eConsoleState& consoleState) override; + QList getLongPressCommandList(const EConsole::eConsoleState& consoleState); + EConsole::eControlType getType() const override; + + void loadLongPressCommands(const EConsole::eConsoleState& consoleState); + void enable() override; + void disable() override; + + void appendCommonLongPressCommandList(const CommandControl_t& commandControl); + + void appendLongPressCommandListBasedOnConsoleState(const QString& consoleState, + const CommandControl_t& commandControl); + + //start timer + void keyDown(); + + //calculate timer between down and up + long keyUp(); + + bool isDown() const; + + bool hasLongPress() const; + + bool hasTimeOutExpired(const long& timeOut); +}; + +#endif //BUTTON_H diff --git a/include/model/csm/core/consoleComponent/ConsoleButton.h b/include/model/csm/core/consoleComponent/ConsoleButton.h new file mode 100644 index 0000000..9264bf4 --- /dev/null +++ b/include/model/csm/core/consoleComponent/ConsoleButton.h @@ -0,0 +1,83 @@ +#ifndef ConsoleButton_H +#define ConsoleButton_H + +#include +#include +#include +#include +#include +#include + +#include "model/csm/core/consoleComponent/ControlAbstract.h" +#include "model/csm/core/consoleComponent/Button.h" +#include "model/csm/core/consoleComponent/Rotary.h" +#include "model/csm/core/consoleComponent/Led.h" +#include "model/csm/dto/HidPacket.h" +#include "model/csm/utils/XmlConsoleConfigReader.h" + +#define LONG_PRESS_TIME_MS 1000 + +/*****************************************************************************/ +/** + * @brief this class is a code vision of each console's item in real + * @author Mohammad Mohsen Talaie + * @details this class modifing the leds, rotary and buttons of each item + * @date 12 jan 2021 + */ +/*****************************************************************************/ +class ConsoleButton : public QObject +{ + Q_OBJECT + +private: + QString _name; + + Button _push; + Button _up; + Button _down; + Rotary _rotary; + + QMutex _longPressLocker; + QList _functionCodes; //init inside ctor + + QList _ledList; + + //this list contain fuction code and corespond commands information. + QMap > _controlCommandList; + QMap > _controlLongPressCommandList; + + EConsole::eConsoleButtonType _ConsolebuttonType; + + void pushDownCheck(Button* btn, const HidPacket_t& data); + + void checkPushUp(Button& btn, const HidPacket_t& data); + + void longPressThread(Button* btn, const HidPacket_t& data); + + int updateControlsEnablity(const Led_t& led); + +public: + //ctor + ConsoleButton(const QDomElement& btnElement); + + EConsole::eConsoleButtonType getConsoleButtonType() const; + QList getFunctionCodes(); + QString getName() const; + + void prepareControlComandList(ControlAbstract* control, + const EConsole::eConsoleState& consoleState); + +signals: + void sendLedStatusToHID(const QMap& ledStatus); + void sendControlCommandToConsoleCore(const QList& commands, + const quint8& functionCode); + void sendControlLongPressCommandToConsoleCore(const QList& commands, + const quint8& functionCode); +//uncrustify off +public slots: +//uncrustify on + void recievePush(const HidPacket_t& data); + void recieveConsoleState(const EConsole::eConsoleState& consoleState, const QString& probType); +}; + +#endif //ConsoleButton_H diff --git a/include/model/csm/core/consoleComponent/ControlAbstract.h b/include/model/csm/core/consoleComponent/ControlAbstract.h new file mode 100644 index 0000000..21c3f3f --- /dev/null +++ b/include/model/csm/core/consoleComponent/ControlAbstract.h @@ -0,0 +1,129 @@ +#ifndef ICONTROL_H +#define ICONTROL_H + +#include +#include + +#include "model/ultrasoundModule/type/ECommandType.h" +#include "model/csm/type/EConsole.h" +#include "model/csm/dto/CommandControl.h" + +/*****************************************************************************/ +/** + * @brief this is an abtract of controls, like buttons and rotaries + * @author Mohammad Mohsen Talaie + * @details + * @date 12 jan 2021 + */ +/*****************************************************************************/ +class ControlAbstract : public QObject +{ + Q_OBJECT + +protected: + bool _exist = false; + bool _enable; + + quint8 _functionCode = 0; + quint8 _ledFunctionCode; + + //This dictionary that store commands depend on csm state + QMap > _commandList; + + /*****************************************************************************/ + /** + * @brief Dtor + */ + /*****************************************************************************/ + virtual ~ControlAbstract() + { + } + +public: + /*****************************************************************************/ + /** + * @brief this fuction return existance of an ControlAbstract. + * @details in detaile this fuction is use full for console button to check its chield is exist + * or not. + * @return existance of ControlAbstract + */ + /*****************************************************************************/ + bool isExist() const + { + return _exist; + } + + /*****************************************************************************/ + /** + * @brief this fuction return enable situation of an ControlAbstract. + * @details in detaile this fuction is use full for console button to check its chield is enable + * or not. + * @return enable situation of ControlAbstract + */ + /*****************************************************************************/ + bool isEnable() const + { + return _enable; + } + + /*****************************************************************************/ + /** + * @brief this function append command to command list of object. + */ + /*****************************************************************************/ + void appendCommandList(const QString& csmState, const CommandControl_t& commandControl) + { + QList temp; + if(!_commandList.contains(EConsole::stringToEConsoleEnum(csmState))) + { + temp.append(commandControl); + _commandList.insert(EConsole::stringToEConsoleEnum(csmState), + temp); + } + else + { + temp = _commandList[EConsole::stringToEConsoleEnum(csmState)]; + temp.append(commandControl); + _commandList[EConsole::stringToEConsoleEnum(csmState)] = temp; + } + } + + /*****************************************************************************/ + /** + * @brief this fuction sets the function code and led function code of Icontrol. + */ + /*****************************************************************************/ + void setFunctionCodes(const quint8& functionCode, const quint8& ledFunctionCode) + { + _functionCode = functionCode; + _ledFunctionCode = ledFunctionCode; + _exist = true; + } + + /*****************************************************************************/ + /** + * @brief return the function code of ControlAbstract + */ + /*****************************************************************************/ + quint8 getFunctionCode() const + { + return _functionCode; + } + + /*****************************************************************************/ + /** + * @brief return the led's function code of ControlAbstract + */ + /*****************************************************************************/ + quint8 getLedFunctionCode() + { + return _ledFunctionCode; + } + + virtual QList getCommandList(const EConsole::eConsoleState& csmState) = 0; + virtual void enable() = 0; + virtual void disable() = 0; + virtual EConsole::eControlType getType() const = 0; +}; + +#endif //ICONTROL_H diff --git a/include/model/csm/core/consoleComponent/Led.h b/include/model/csm/core/consoleComponent/Led.h new file mode 100644 index 0000000..9414951 --- /dev/null +++ b/include/model/csm/core/consoleComponent/Led.h @@ -0,0 +1,23 @@ +#ifndef LED_H +#define LED_H + +#include +#include + +#include "model/csm/type/EConsole.h" + +typedef struct LedStatus_T +{ + EConsole::eConsoleState csmState; + QString probType; + quint8 value; +}LedStatus_T; + +typedef struct Led_t +{ + QString name; + quint8 functionCode; + QList ledStatus; +}Led_t; + +#endif //LED_H diff --git a/include/model/csm/core/consoleComponent/Rotary.h b/include/model/csm/core/consoleComponent/Rotary.h new file mode 100644 index 0000000..7de2b9d --- /dev/null +++ b/include/model/csm/core/consoleComponent/Rotary.h @@ -0,0 +1,23 @@ +#ifndef ROTARY_H +#define ROTARY_H + +#include "model/csm/core/consoleComponent/ControlAbstract.h" + +/*****************************************************************************/ +/** + * @brief Rotary class + * @author Mohammad Mohsen Talaie + * @details + * @date 12 Jan 2020 + */ +/*****************************************************************************/ +class Rotary : public ControlAbstract +{ +public: + QList getCommandList(const EConsole::eConsoleState& consoleState) override; + EConsole::eControlType getType()const override; + void enable() override; + void disable() override; +}; + +#endif //ROTARY_H diff --git a/include/model/csm/core/trackballComponent/CenterBall.h b/include/model/csm/core/trackballComponent/CenterBall.h new file mode 100644 index 0000000..ca63e12 --- /dev/null +++ b/include/model/csm/core/trackballComponent/CenterBall.h @@ -0,0 +1,29 @@ +#ifndef CENTERBALL_H +#define CENTERBALL_H + +#include "model/csm/core/trackballComponent/TrackballItem.h" + +/*****************************************************************************/ +/** + * @brief this is a code vision of center ball of trackball + * @author Mohammad Mohsen Talaie + * @details + * @date 12 jan 2021 + */ +/*****************************************************************************/ +class CenterBall : public TrackballItem +{ +public: + /*****************************************************************************/ + /** + * @brief ctor. this funciton set type of trackball item + */ + /*****************************************************************************/ + inline CenterBall(const QString& name) : TrackballItem(EConsole::eTrackballItemType::centerBall, + name) + { + _type = EConsole::eTrackballItemType::centerBall; + } +}; + +#endif //CENTERBALL_H diff --git a/include/model/csm/core/trackballComponent/HidButton.h b/include/model/csm/core/trackballComponent/HidButton.h new file mode 100644 index 0000000..145d909 --- /dev/null +++ b/include/model/csm/core/trackballComponent/HidButton.h @@ -0,0 +1,42 @@ +#ifndef HIDBUTTON_H +#define HIDBUTTON_H + +#include "model/csm/core/trackballComponent/TrackballItem.h" + +/*****************************************************************************/ +/** + * @brief class of trackball's hid button + * @author Mohammad Mohsen Talaie + * @details + * @date 21 sep 2021 + */ +/*****************************************************************************/ +class HidButton : public TrackballItem +{ +private: + quint8 _functionCode; + +public: + /*****************************************************************************/ + /** + * @brief ctor. set type of control + */ + /*****************************************************************************/ + HidButton(QString name) : TrackballItem(EConsole::eTrackballItemType::hidButton, name) + { + _type = EConsole::eTrackballItemType::hidButton; + _functionCode = 0; + } + + quint8 getFucitonCode() const + { + return _functionCode; + } + + void setFunctionCode(const quint8 fCode) + { + this->_functionCode = fCode; + } +}; + +#endif //HIDBUTTON_H diff --git a/include/model/csm/core/trackballComponent/MiceButton.h b/include/model/csm/core/trackballComponent/MiceButton.h new file mode 100644 index 0000000..94b9385 --- /dev/null +++ b/include/model/csm/core/trackballComponent/MiceButton.h @@ -0,0 +1,23 @@ +#ifndef MICEBUTTON_H +#define MICEBUTTON_H + +#include "model/csm/core/trackballComponent/TrackballItem.h" + +/*****************************************************************************/ +/** + * @brief class of mice button of trackball + * @author Mohammad Mohsen Talaie + * @details + * @date 12 jan 2021 + */ +/*****************************************************************************/ +class MiceButton : public TrackballItem +{ +public: + MiceButton(QString name) : TrackballItem(EConsole::eTrackballItemType::miceButton, name) + { + _type = EConsole::eTrackballItemType::miceButton; + } +}; + +#endif //MICEBUTTON_H diff --git a/include/model/csm/core/trackballComponent/TrackballItem.h b/include/model/csm/core/trackballComponent/TrackballItem.h new file mode 100644 index 0000000..1eec024 --- /dev/null +++ b/include/model/csm/core/trackballComponent/TrackballItem.h @@ -0,0 +1,51 @@ +#ifndef ITRACKBALLITEM_H +#define ITRACKBALLITEM_H + +#include + +#include "model/csm/type/EConsole.h" +#include "model/csm/dto/ItemValue.h" +#include "model/csm/dto/CommandControl.h" + +/*****************************************************************************/ +/** + * @brief trackball item class. this class is the father of mice button, hid button and center ball. + * @author Mohammad Mohsen Talaie + * @details + * @date 12 jan 2021 + */ +/*****************************************************************************/ +class TrackballItem +{ +protected: + EConsole::eTrackballItemType _type; + QMap > _commandContainer; + QMap > _configContainer; + QString _name; + +public: + TrackballItem(const EConsole::eTrackballItemType& type, const QString& name); + + ~TrackballItem() + { + } + + EConsole::eTrackballItemType getType(); + + void appendCommandContainer(const EConsole::eTrackballState& trackballState, + const QList& commandList); + void appendConfigContainer(const EConsole::eTrackballState& trackballState, + const QList& configList); + void appendConfigContainer(const EConsole::eTrackballState& trackballState, + const ItemValue_t& config); + void appendCommandContainer(const QString& trackballStateName, + const CommandControl_t& command); + + QString getName()const; + + QList getCommand(const EConsole::eTrackballState& state)const; + + QList getConfig(const EConsole::eTrackballState& state)const; +}; + +#endif //ITRACKBALLITEM_H diff --git a/include/model/csm/dto/CommandControl.h b/include/model/csm/dto/CommandControl.h new file mode 100644 index 0000000..90f2a8f --- /dev/null +++ b/include/model/csm/dto/CommandControl.h @@ -0,0 +1,24 @@ +#ifndef COMMANDCONTROL_H +#define COMMANDCONTROL_H + +#include +#include "model/ultrasoundModule/type/ECommandType.h" + +typedef struct RecieverContent_t +{ + QString reciever; + QList content; +}RecieverContent_t; + +typedef struct CommandControl_t +{ + ECommandType::eCommandType commandType; + RecieverContent_t recieverInfo; + int value; + int timeTag; +}CommandControl_t; + +Q_DECLARE_METATYPE(CommandControl_t) +Q_DECLARE_METATYPE(QList) + +#endif //COMMANDCONTROL_H diff --git a/include/model/csm/dto/HidPacket.h b/include/model/csm/dto/HidPacket.h new file mode 100644 index 0000000..dbf3c2c --- /dev/null +++ b/include/model/csm/dto/HidPacket.h @@ -0,0 +1,18 @@ +#ifndef PACKET_H +#define PACKET_H + +#include + +typedef struct HidPacket_t +{ + quint8 header; + quint8 dataLength; + quint8 type; + quint8 functionCode; + quint16 data; + quint16 timeTag; +}HidPacket_t; + +Q_DECLARE_METATYPE(HidPacket_t) + +#endif //PACKET_H diff --git a/include/model/csm/dto/ItemValue.h b/include/model/csm/dto/ItemValue.h new file mode 100644 index 0000000..ff450f3 --- /dev/null +++ b/include/model/csm/dto/ItemValue.h @@ -0,0 +1,17 @@ +#ifndef ITEMVALUE_H +#define ITEMVALUE_H + +#include +#include + +typedef struct ItemValue_t +{ + QString value; + bool enable; + bool active; +}ItemValue_t; + +Q_DECLARE_METATYPE(ItemValue_t) +Q_DECLARE_METATYPE(QList) + +#endif // ITEMVALUE_H diff --git a/include/model/csm/dto/TrackballConfig.h b/include/model/csm/dto/TrackballConfig.h new file mode 100644 index 0000000..4a5a7ce --- /dev/null +++ b/include/model/csm/dto/TrackballConfig.h @@ -0,0 +1,24 @@ +#ifndef TRACKBALLCONFIG_H +#define TRACKBALLCONFIG_H + +#include +#include + +#include "model/csm/dto/ItemValue.h" + +typedef struct TrackballConfig_t +{ + QList middleTop; + QList topLeft; + QList topRight; + QList left; + QList right; + QList bottomRight; + QList bottomLeft; + QList middleBottom; + QList centerBall; +}TrackballConfig_t; + +Q_DECLARE_METATYPE(TrackballConfig_t) + +#endif //TRACKBALLCONFIG_H diff --git a/include/model/csm/exception/CsmException.h b/include/model/csm/exception/CsmException.h new file mode 100644 index 0000000..4b446af --- /dev/null +++ b/include/model/csm/exception/CsmException.h @@ -0,0 +1,53 @@ +#ifndef CSMEXCEPTION_H +#define CSMEXCEPTION_H + +#include + +#include "logger/ESeverityLevel.h" +#include "model/csm/exception/CsmExceptionDef.h" + +class CsmException : public std::exception +{ +private: + quint32 _errId; + QString _innerMessage; + +public: + explicit CsmException(quint32 errId) + { + _errId = errId; + } + + explicit CsmException(quint32 errId, QString innerMessage) + { + _errId = errId; + _innerMessage = innerMessage; + } + + const char* what() const noexcept override + { + return HwErrors::getErrorMessage(_errId).toStdString().c_str(); + } + + ESeverityLevel::eSeverityLevel getSeverityLevel() const + { + return HwErrors::getSeverityLevel(_errId); + } + + quint32 errId() const + { + return _errId; + } + + QString getInnerMessage() const + { + return _innerMessage; + } + + QString getMessage() const + { + return HwErrors::getErrorMessage(_errId); + } +}; + +#endif //CSMEXCEPTION_H diff --git a/include/model/csm/exception/CsmExceptionDef.h b/include/model/csm/exception/CsmExceptionDef.h new file mode 100644 index 0000000..0372099 --- /dev/null +++ b/include/model/csm/exception/CsmExceptionDef.h @@ -0,0 +1,43 @@ +#ifndef CSMEXCEPTIONDEF_H +#define CSMEXCEPTIONDEF_H + +#include + +#include "logger/ESeverityLevel.h" + +#define ECHO_FAILED 0 +#define WRITE_ERROR 1 +#define HID_NOT_FOUND 2 + +struct HwErrors +{ + static QString getErrorMessage(quint32 id) + { + switch(id) + { + case ECHO_FAILED: + return + "The panel micro did not responsed within time limit. Restart the device and contact the service if problem still persists"; + + case WRITE_ERROR: + return "Could not send HID data to the panel"; + + case HID_NOT_FOUND: + return + "HID device not found, make sure the usb cable is connected and device is powered on"; + } + } + + static ESeverityLevel::eSeverityLevel getSeverityLevel(quint32 id) + { + switch(id) + { + case ECHO_FAILED: + case WRITE_ERROR: + case HID_NOT_FOUND: + return ESeverityLevel::Error; + } + } +}; + +#endif //CSMEXCEPTIONDEF_H diff --git a/include/model/csm/type/EConsole.h b/include/model/csm/type/EConsole.h new file mode 100644 index 0000000..257e4ac --- /dev/null +++ b/include/model/csm/type/EConsole.h @@ -0,0 +1,133 @@ +#ifndef ECONSOLE_H +#define ECONSOLE_H + +#include +#include + +class EConsole : public QObject +{ + Q_OBJECT + +private: + //Private constructor prevent the enumeration class from being instantiated + explicit EConsole(QObject* parent = nullptr); + +public: + enum eControlType + { + button, + rotary + }; + + enum eConsoleButtonType : int + { + pushButton = 1, + rotaryButton = 2, + rotaryPushButton = 3, + rotaryPushButtonUpDown = 5 + }; + + enum eCsmInterruptType : quint8 + { + push, + longPress, + tabChanged, + touchPanel, + deviceInterrupt, + mouseMove + }; + + Q_ENUM(eCsmInterruptType) + + enum eConsoleState : quint8 + { + BMode, + BMode_Freeze, + BMode_Freeze_CineTab, + BMode_Freeze_Pointer, + BMode_Pointer, + Test + }; + + Q_ENUM(eConsoleState) + + enum eTrackballMode : quint8 + { + trackball, + mouse + }; + + Q_ENUM(eTrackballMode) + + enum eTrackballState : quint8 + { + tBMode, + tBMode_Freeze, + tTest, + tCine, + tHDZoom + }; + + Q_ENUM(eTrackballState) + + enum eTrackballItemType : quint8 + { + miceButton, + hidButton, + centerBall + }; + + Q_ENUM(eTrackballItemType) + + enum eTrackballItem : quint8 + { + left, + right, + top, + bottom, + topLeft, + topRight, + bottomLeft, + bottomRight, + center + }; + + Q_ENUM(eTrackballItem) + + template + static QString eConsoleEnumToString(const EnumType inputEnum) + { + return QString(QMetaEnum::fromType().valueToKey(inputEnum)); + } + + template + static EnumType stringToEConsoleEnum(QString name) + { + auto&& metaEnum = QMetaEnum::fromType(); + auto data = name.toUtf8().constData(); + auto ret = static_cast(metaEnum.keyToValue(data)); + + return ret; + } + + template + static quint8 consoleEnumToQuint(const EnumType qtEnum) + { + return QMetaEnum::fromType().value(qtEnum); + } + + template + static EnumType consoleQuintToEnum(const quint8 intEnum) + { + auto&& metaEnum = QMetaEnum::fromType(); + + return static_cast(intEnum); + } +}; + +template EConsole::eConsoleState EConsole::consoleQuintToEnum( + const quint8 intEnum); +template EConsole::eTrackballState EConsole::consoleQuintToEnum( + const quint8 intEnum); + +#endif //ECONSOLE_H diff --git a/include/model/csm/type/Graph.h b/include/model/csm/type/Graph.h new file mode 100644 index 0000000..2ef1202 --- /dev/null +++ b/include/model/csm/type/Graph.h @@ -0,0 +1,77 @@ +#ifndef GRAPH_H +#define GRAPH_H + +#include +#include + +#include "Node.h" +#include "EConsole.h" + +class GraphException : public QException +{ +private: + QString message; + +public: + GraphException(QString const& text = " ") noexcept + : message(text) + { + } + + GraphException(const GraphException& re) + { + this->message = re.message; + } + + ~GraphException() override + { + } + + void raise() const override { + throw*this; + } + + GraphException* clone() const override { + return new GraphException(*this); + } + + const char* what() const noexcept override { + return this->message.toStdString().c_str(); + } +}; + +/*****************************************************************************/ +/** + * @brief class for processing graph + * @author Mohammad Mohsen Talaie + * @details + * @date 13 JAN 2021 + */ +/*****************************************************************************/ +class Graph +{ + QList _nodeList; + +public: + Graph(); + + bool existNode(QString nodeName); + bool existNode(Node* node); + QList getNodeChildren(QString nodeName); + + Node* getNodeByName(QString name); + + template + Node* getNode(EnumType state); + + bool insertEdge(Node* source, + Node* destination, + EConsole::eCsmInterruptType interrupt, + QString vaule); + bool insertEdge(QString sourceName, + QString destinationName, + EConsole::eCsmInterruptType interrupt, + QString value); +}; + +#endif //GRAPH_H diff --git a/include/model/csm/type/Node.h b/include/model/csm/type/Node.h new file mode 100644 index 0000000..630103f --- /dev/null +++ b/include/model/csm/type/Node.h @@ -0,0 +1,35 @@ +#ifndef NODE_H +#define NODE_H + +#include + +#include "model/csm/type/Transition.h" +#include "model/csm/type/EConsole.h" + +/*****************************************************************************/ +/** + * @brief the class for node processing + * @author Mohammad Mohsen Talaie + * @details + * @date 13 JAN 2021 + */ +/*****************************************************************************/ +class Node +{ +private: + QList _transitionList; + QString _name; + quint8 _state; + QList _childList; + +public: + Node(QString name); + QString getName(); + QList getChildren(); + Node* getDestination(EConsole::eCsmInterruptType interrupt, QString value); + bool hasTransiton(Transition_t inputTransition); + bool appendTransition(Node* destiantion, EConsole::eCsmInterruptType interrupt, QString value); + quint8 getState(); +}; + +#endif //NODE_H diff --git a/include/model/csm/type/Transition.h b/include/model/csm/type/Transition.h new file mode 100644 index 0000000..f6a9e84 --- /dev/null +++ b/include/model/csm/type/Transition.h @@ -0,0 +1,17 @@ +#ifndef TRANSITION_H +#define TRANSITION_H + +#include + +#include "model/csm/type/EConsole.h" + +class Node; +typedef struct Transition_t +{ + Node* source; + Node* Destination; + EConsole::eCsmInterruptType interruptType; + QString value; +}Transition_t; + +#endif //TRANSITION_H diff --git a/include/model/csm/utils/MouseEventFilter.h b/include/model/csm/utils/MouseEventFilter.h new file mode 100644 index 0000000..2e08c71 --- /dev/null +++ b/include/model/csm/utils/MouseEventFilter.h @@ -0,0 +1,27 @@ +#ifndef MOUSEEVENTFILTER_H +#define MOUSEEVENTFILTER_H + +#include +#include + +#include "model/csm/core/TrackballCore.h" + +class MouseEventFilter : public QObject +{ + Q_OBJECT + +public: + bool eventFilter(QObject* obj, QEvent* event) override; + MouseEventFilter(); +}; + +class TrackballMouseEventFilter : public QObject +{ + Q_OBJECT + +public: + bool eventFilter(QObject* obj, QEvent* event) override; + TrackballMouseEventFilter(); +}; + +#endif //MOUSEEVENTFILTER_H diff --git a/include/model/csm/utils/XCursorSetter.h b/include/model/csm/utils/XCursorSetter.h new file mode 100644 index 0000000..b23ef34 --- /dev/null +++ b/include/model/csm/utils/XCursorSetter.h @@ -0,0 +1,43 @@ +#ifndef XCURSORSETTER_H +#define XCURSORSETTER_H + +#include +#include +#include +#include +#include +#include + +using namespace std; + +class XCursorSetter +{ + Display* dpy; + int screen; + Window win; + + int ptrid; + char *shape_name; + int shape; + int size; + char *theme; + XcursorImage *image; + Cursor cursor; +// ./xicursorset 2 right_ptr whiteglass + + void hide() + { + ptrid = std::atoi("19"); + shape_name = "right_ptr"; + + shape = XcursorLibraryShape(shape_name); + if (shape < 0) + { + fprintf(stderr, "Invalid shape name.\n"); + return; + } + } + + +}; +#endif // XCURSORSETTER_H diff --git a/include/model/csm/utils/XmlConsoleConfigReader.h b/include/model/csm/utils/XmlConsoleConfigReader.h new file mode 100644 index 0000000..9aaf3df --- /dev/null +++ b/include/model/csm/utils/XmlConsoleConfigReader.h @@ -0,0 +1,63 @@ +#ifndef XMLCONFIGREADER_H +#define XMLCONFIGREADER_H + +#include +#include + +#include "model/csm/core/consoleComponent/Button.h" +#include "model/csm/core/consoleComponent/Rotary.h" +#include "model/csm/core/consoleComponent/Led.h" +#include "model/csm/dto/CommandControl.h" +#include "logger/Logger.h" +#include "model/csm/type/Node.h" +#include "model/csm/type/Graph.h" + +class XmlConsoleConfigReader +{ +private: + inline void handleError(ESeverityLevel::eSeverityLevel severityLevel, + ELogID::eLogID logID, + QString logText, + bool emitThrow = true) const; + + QDomDocument _xmlDoc; + QString _xmlAddress; + QDomElement _root; + QDomElement _console; + QList _consoleButtons; + +public: + XmlConsoleConfigReader(QString address); + + QDomElement getConsole(); + QList getConsoleButtons(); + + //Console Button + static QList getAllControls(QDomElement consoleButton); + static QDomElement getRotary(QDomElement consoleButton); + static QList getPushButton(QDomElement consoleButton); + static QList getLeds(QDomElement console); + + static void initControl(QDomElement controlElement, Button* btn); + static void initControl(QDomElement controlElement, Rotary* rotary); + static void initControls(QList controlsElement, + Button* push, + Button* up, + Button* down, + Rotary* rotary); + + static void initLeds(QList ledsElements, QList* leds); + + static QString initConsoleButton(QDomElement consoleButtonElement, + Button* push, + Button* up, + Button* down, + Rotary* rotary, + QList* leds); + static void getControlCommonLongPressCommands(QDomElement controlElement, Button* btn); + static void getButtonStateCommands(QDomElement controlElement, Button* btn); + static void getButtonLongPressCommandBasedOnConsoleState(QDomNode consoleState, Button* btn); + static void getButtonShortPressCommands(QDomNode consoleState, Button* btn); +}; + +#endif //XMLCONFIGREADER_H diff --git a/include/model/csm/utils/XmlGraphStateReader.h b/include/model/csm/utils/XmlGraphStateReader.h new file mode 100644 index 0000000..9378f04 --- /dev/null +++ b/include/model/csm/utils/XmlGraphStateReader.h @@ -0,0 +1,49 @@ +#ifndef XMLGRAPHSTATEREADER_H +#define XMLGRAPHSTATEREADER_H +#include +#include + +#include "model/csm/dto/CommandControl.h" +#include "logger/Logger.h" +#include "model/csm/type/Node.h" +#include "model/csm/type/Graph.h" + +class XmlGraphStateReader +{ +private: + QDomDocument _xmlDoc; + QString _xmlAddress; + QDomElement _root; + //gragh nodes + QDomElement _state; + QList _commonDestinations; + QList _specificStates; + + inline void handleError(ESeverityLevel::eSeverityLevel severityLevel, + ELogID::eLogID logID, + QString logText, + bool emitThrow = true) const; + +public: + XmlGraphStateReader(QString address); + //Graph + QDomElement getState(); + QList getCommonDestinations(); + QList getSpeciticStates(); + + static QList getStateDestination(QDomElement state); + static void addEdge(QDomElement state, + QList commonDestinations, + Graph* stateGraph); + static void initGraph(Graph* stateGraph, + QList states, + QList commonDestinations); + static void addSpeciticEdge(QDomElement state, QList desinations, + Graph* stateGraph); + + static void addCommonEdge(QDomElement state, + QList commonDestinations, + Graph* stateGraph); +}; + +#endif //XMLGRAPHSTATEREADER_H diff --git a/include/model/csm/utils/XmlTrackballConfigReader.h b/include/model/csm/utils/XmlTrackballConfigReader.h new file mode 100644 index 0000000..8a46442 --- /dev/null +++ b/include/model/csm/utils/XmlTrackballConfigReader.h @@ -0,0 +1,49 @@ +#ifndef XMLTRACKBALLCONFIGREADER_H +#define XMLTRACKBALLCONFIGREADER_H + +#include +#include + +#include "logger/Logger.h" +#include "model/csm/core/trackballComponent/TrackballItem.h" + +/*****************************************************************************/ +/** + * @brief + * @author Mohammad Mohsen Talaie + * @details + * @date 13 JAN 2021 + */ +/*****************************************************************************/ +class XmlTrackballConfigReader +{ +private: + inline void handleError(ESeverityLevel::eSeverityLevel severityLevel, + ELogID::eLogID logID, + QString logText, + bool emitThrow = true) const; + + QDomDocument _xmlDoc; + QString _xmlAddress; + QDomElement _root; + QDomElement _trackball; + QList _trackballItems; + +public: + XmlTrackballConfigReader(QString address); + + QDomElement getTrackball(); + QList getTrackballItems(); + + static QDomElement getChildElement(const QDomElement fatherElement, const QString elementName); + static QList getChildrenElemets(const QDomElement fatherElement, + const QString elementsName); + static QString getElementAttribute(const QDomElement element, const QString attributeName); + static bool getElementBooleanAttribute(QDomElement element, QString bollAttrName); + static void initTrackballItem(TrackballItem* tbItem, const QDomElement itemElement); + static void initTrackballItems(QList trackballItems, + const QDomElement trackballElement); + static TrackballItem* findItem(const QList trackballItems, const QString name); +}; + +#endif //XMLTRACKBALLCONFIGREADER_H diff --git a/include/model/databaseManager/DatabaseManager.h b/include/model/databaseManager/DatabaseManager.h new file mode 100644 index 0000000..b835cf5 --- /dev/null +++ b/include/model/databaseManager/DatabaseManager.h @@ -0,0 +1,35 @@ +#ifndef DATABASEMANAGER_H +#define DATABASEMANAGER_H + +#include +#include + +#include "model/ultrasoundModule/UsModule.h" +#include "config/Configuration.h" +#include "model/databaseManager/core/DatabaseManagerCore.h" + +/*************************************************************************************************/ +/** + * @brief Is responsible for database management i.e. CRUD operations on tables + * @details This module will take commands from other classes and does the database stuff, for + * example it will read requested data or writes new ones, at the first run it also creates the DB + * scheme with provided files + * @author Mohammad Mohsen Talaie + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +class DatabaseManager : public UsModule +{ + Q_OBJECT + US_MODULE + SINGLETON(DatabaseManager) + +private: + DatabaseManagerCore* _core; + +public: + DatabaseManager(); + ~DatabaseManager() override; +}; + +#endif //DATABASEMANAGER_H diff --git a/include/model/databaseManager/core/DatabaseManagerCore.h b/include/model/databaseManager/core/DatabaseManagerCore.h new file mode 100644 index 0000000..65e22c1 --- /dev/null +++ b/include/model/databaseManager/core/DatabaseManagerCore.h @@ -0,0 +1,66 @@ +#ifndef DATABASEMANAGERCORE_H +#define DATABASEMANAGERCORE_H + +#include +#include + +#include "model/databaseManager/utils/XmlReader.h" +#include "model/databaseManager/type/EDatabaseRequest.h" +#include "model/databaseManager/dto/ProbeProperties/DbmProbeProperties.h" +#include "model/databaseManager/dto/ProbeProperties/DbmApplicatoin.h" +#include "model/databaseManager/dto/ProbeProperties/DbmPreset.h" +#include "model/databaseManager/dto/ProbeProperties/DbmPresetValue.h" +#include "model/databaseManager/dto/ProbeProperties/DbmLastConfig.h" +#include "model/databaseManager/dto/System/DbmSysParameters.h" +#include "model/databaseManager/dto/System/DbmGrayMap.h" +#include "model/databaseManager/dto/System/DbmTgc.h" +#include "model/databaseManager/dto/System/DbmTintMap.h" +#include "model/databaseManager/dto/System/DbmSri.h" +#include "model/databaseManager/dto/System/DbmDynamicContrast.h" +#include "model/databaseManager/dto/System/DbmCriFilter.h" +#include "model/databaseManager/dto/System/DbmEnhance.h" +#include "model/databaseManager/dto/Hardware/DbmLineFilter.h" +#include "model/databaseManager/dto/Hardware/DbmLpf.h" +#include "model/databaseManager/dto/Hardware/DbmApodizationLut.h" +#include "model/databaseManager/dto/User/DbmUser.h" +#include "model/databaseManager/dto/User/DbmUserGrayMap.h" +#include "model/databaseManager/dto/User/DbmUserTgc.h" +#include "model/databaseManager/core/DatabaseManagerNames.h" + +/*************************************************************************************************/ +/** + * @brief Database manager core class + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +class DatabaseManagerCore : public QObject +{ + Q_OBJECT + +private: + static QMutex _locker; + XmlReader* _xmlReader; + XmlReader* _xmlDataReader; + QSqlDatabase _databaseDriver = QSqlDatabase::addDatabase("QSQLITE"); + + QString getDatabaseHomeDirectory(); + QString createDbName(QString dbName); + DbmDtoGrayMap appendUserGrayMapToMainGrayMapList(const QVariant& userGrayVar, + QVariant& grayVar); + DbmDtoTgc appendUserTgcToMainTgcList(const QVariant& userTgcVar, QVariant& tgcVar); + +public: + DatabaseManagerCore(); + ~DatabaseManagerCore(); + + void init(); + + QPair read(EDatabaseRequest::eDatabaseRequest databaseRequest, + QList args); + bool write(EDatabaseRequest::eDatabaseRequest databaseRequest, + QList args); +}; + +#endif //DATABASEMANAGERCORE_H diff --git a/include/model/databaseManager/core/DatabaseManagerNames.h b/include/model/databaseManager/core/DatabaseManagerNames.h new file mode 100644 index 0000000..096c000 --- /dev/null +++ b/include/model/databaseManager/core/DatabaseManagerNames.h @@ -0,0 +1,11 @@ +#ifndef DATABASEMANAGERNAMES_H +#define DATABASEMANAGERNAMES_H + +#define DB_FILE_EXT ".db" + +#define PROBE_DB_NAME "ProbeProperties" +#define SYSTEM_DB_NAME "System" +#define HW_DB_NAME "Hardware" +#define USER_DB_NAME "UserData" + +#endif //DATABASEMANAGERNAMES_H diff --git a/include/model/databaseManager/dto/Hardware/DbmApodizationLut.h b/include/model/databaseManager/dto/Hardware/DbmApodizationLut.h new file mode 100644 index 0000000..813e77a --- /dev/null +++ b/include/model/databaseManager/dto/Hardware/DbmApodizationLut.h @@ -0,0 +1,55 @@ +#ifndef DBMAPODIZATIONLUT_H +#define DBMAPODIZATIONLUT_H + +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" + +/*************************************************************************************************/ +/** + * @brief Database dto structure for ApodizationLut + * @author Mohammad Mohsen Talaie + * @details + * @date 07 feb 2021 + */ +/*************************************************************************************************/ +typedef struct DbmDtoApodizationLut +{ + QList case1; + QList case2; + QList case3; + QList case4; + bool isActive; +}DbmDtoApodizationLut; + +Q_DECLARE_METATYPE(DbmDtoApodizationLut) + +/*************************************************************************************************/ +/** + * @brief Database class for ApodizationLut + * @author Mohammad Mohsen Talaie + * @details + * @date 2021 + */ +/*************************************************************************************************/ +class DbmApodizationLut +{ +public: + static bool getApodizationLut(QSqlTableModel* tableModel, DbmDtoApodizationLut& apodizationLut) + { + tableModel->setTable("ApodizationLut"); + tableModel->setFilter(QString("isActive = 1")); + bool ret = tableModel->select(); + INIT_LIST(apodizationLut, tableModel, case1, Int, 0); + INIT_LIST(apodizationLut, tableModel, case2, Int, 0); + INIT_LIST(apodizationLut, tableModel, case3, Int, 0); + INIT_LIST(apodizationLut, tableModel, case4, Int, 0); + + return ret; + } +}; + +#endif //DBMAPODIZATIONLUT_H diff --git a/include/model/databaseManager/dto/Hardware/DbmLineFilter.h b/include/model/databaseManager/dto/Hardware/DbmLineFilter.h new file mode 100644 index 0000000..4a8e7a5 --- /dev/null +++ b/include/model/databaseManager/dto/Hardware/DbmLineFilter.h @@ -0,0 +1,73 @@ +#ifndef DBMLINEFILTER_H +#define DBMLINEFILTER_H + +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" + +/*************************************************************************************************/ +/** + * @brief Database dto structu for Line filter + * @author MMT + * @details + * @date 06 feb 2021 + */ +/*************************************************************************************************/ +typedef struct DbmDtoLineFilter +{ + QList > lineFilterData; + bool isActive; +}DbmDtoLineFilter; + +Q_DECLARE_METATYPE(DbmDtoLineFilter) + +class DbmLineFilter +{ +public: + static bool getLineFilter(QSqlTableModel* tableModel, DbmDtoLineFilter& lineFilter) + { + tableModel->setTable("LineFilter"); + tableModel->setFilter(QString("isActive = 1")); + bool ret = tableModel->select(); + if(!ret) + { + return ret; + } + + auto __off = + tableModel->record(0).value("off").toString().split(',', QString::SkipEmptyParts); + auto __low = + tableModel->record(0).value("low").toString().split(',', QString::SkipEmptyParts); + auto __hi = + tableModel->record(0).value("hi").toString().split(',', QString::SkipEmptyParts); + + QList temp; + for(int j = 0; j < __off.length(); ++j) + { + temp.append(__off[j].toDouble()); + } + lineFilter.lineFilterData.append(temp); + + temp.clear(); + for(int j = 0; j < __low.length(); ++j) + { + temp.append(__low[j].toDouble()); + } + lineFilter.lineFilterData.append(temp); + + temp.clear(); + for(int j = 0; j < __hi.length(); ++j) + { + temp.append(__hi[j].toDouble()); + } + lineFilter.lineFilterData.append(temp); + + return ret; + } +}; + +#endif //DBMLINEFILTER_H diff --git a/include/model/databaseManager/dto/Hardware/DbmLpf.h b/include/model/databaseManager/dto/Hardware/DbmLpf.h new file mode 100644 index 0000000..0eea4e2 --- /dev/null +++ b/include/model/databaseManager/dto/Hardware/DbmLpf.h @@ -0,0 +1,58 @@ +#ifndef DBMLPF_H +#define DBMLPF_H +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" +#include "model/databaseManager/type/EAlgorithmType.h" + +/*************************************************************************************************/ +/** + * @brief Database dto structure for LPF data + * @author Mohammad Mohsen Talaie + * @details + * @date 06 feb 2021 + */ +/*************************************************************************************************/ +typedef struct DbmDtoLpf +{ +public: + QList lpf; + QList lpfCoef; + QList lpfKaiser; + QList lpfKaiser2; + bool isActive; +}DbmDtoLpf; + +Q_DECLARE_METATYPE(DbmDtoLpf) + +/*************************************************************************************************/ + +/** + * @brief Database class for LPF data + * @author Mohammad Mohsen Talaie + * @details + * @date 06 feb 2021 + */ +/*************************************************************************************************/ +class DbmLpf +{ +public: + static bool getLpfParams(QSqlTableModel* tableModel, DbmDtoLpf& lpfData) + { + tableModel->setTable("LPF"); + tableModel->setFilter(QString("isActive = 1")); + bool ret = tableModel->select(); + INIT_LIST(lpfData, tableModel, lpf, Double, 0); + INIT_LIST(lpfData, tableModel, lpfCoef, Double, 0); + INIT_LIST(lpfData, tableModel, lpfKaiser, Double, 0); + INIT_LIST(lpfData, tableModel, lpfKaiser2, Double, 0); + + return ret; + } +}; + +#endif //DBMLPF_H diff --git a/include/model/databaseManager/dto/ProbeProperties/DbmApplicatoin.h b/include/model/databaseManager/dto/ProbeProperties/DbmApplicatoin.h new file mode 100644 index 0000000..b647829 --- /dev/null +++ b/include/model/databaseManager/dto/ProbeProperties/DbmApplicatoin.h @@ -0,0 +1,66 @@ +#ifndef DBMAPPLICATOIN_H +#define DBMAPPLICATOIN_H + +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" + +/*************************************************************************************************/ +/** + * @brief Database dto structur for Application + * @author MMT + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +typedef struct DbmDtoApplication +{ + int ID; + int Prob_id; + int orderNum; + int Owner_id; + QString name; + QString showText; + QString image; +}DbmDtoApplication; + +Q_DECLARE_METATYPE(DbmDtoApplication) + +/*************************************************************************************************/ +/** + * @brief Database Class for Appliction + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +class DbmApplication +{ +public: + static bool getApplicationsByProbeId(QString ID, QSqlTableModel* tableModel, + QList& applications) + { + tableModel->setTable("Application"); + tableModel->setFilter(QString("Probe_id = '%1'").arg(ID)); + bool ret = tableModel->select(); + DbmDtoApplication applicationIns; + for(int i = 0; i < tableModel->record().count(); ++i) + { + INIT_SINGLE(applicationIns, tableModel, ID, Int, i); + INIT_SINGLE(applicationIns, tableModel, Prob_id, Int, i); + INIT_SINGLE(applicationIns, tableModel, Owner_id, Int, i); + INIT_SINGLE(applicationIns, tableModel, orderNum, Int, i); + INIT_SINGLE(applicationIns, tableModel, image, String, i); + INIT_SINGLE(applicationIns, tableModel, name, String, i); + INIT_SINGLE(applicationIns, tableModel, showText, String, i); + applications.append(applicationIns); + } + + return ret; + } +}; + +#endif //DBMAPPLICATOIN_H diff --git a/include/model/databaseManager/dto/ProbeProperties/DbmLastConfig.h b/include/model/databaseManager/dto/ProbeProperties/DbmLastConfig.h new file mode 100644 index 0000000..c87deea --- /dev/null +++ b/include/model/databaseManager/dto/ProbeProperties/DbmLastConfig.h @@ -0,0 +1,138 @@ +#ifndef DBMLASTCONFIG_H +#define DBMLASTCONFIG_H +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" + +#define GET_MAX_ID_FILTER "ID = (SELECT max(ID) FROM LastConfig)" + +/*************************************************************************************************/ +/** + * @brief Database dto structur for LastConfig + * @author MMT + * @details + * @date 08 mar 2021 + */ +/*************************************************************************************************/ +typedef struct DbmDtoLastConfig +{ + int ID; + int Probe_id; + int Application_id; + int Preset_id; + int ProbePortIndex; + int Owner_id; +}DbmDtoLastConfig; + +Q_DECLARE_METATYPE(DbmDtoLastConfig) + +/*************************************************************************************************/ +/** + * @brief Database class for LastConfig + * @author Mohammad Mohsen Talaie + * @details + * @date 08 mar 2021 + */ +/*************************************************************************************************/ +class DbmLastConfig +{ +public: + static bool getLastConfig(QSqlTableModel* tableModel, + DbmDtoLastConfig& lastConfig) + { + auto filter = GET_MAX_ID_FILTER; + bool ret = selectFromLastConfig(tableModel, filter); + DbmDtoLastConfig lastConfigIns; + + if(tableModel->rowCount() > 0) + { + INIT_SINGLE(lastConfigIns, tableModel, ID, Int, 0); + INIT_SINGLE(lastConfigIns, tableModel, Application_id, Int, 0); + INIT_SINGLE(lastConfigIns, tableModel, Probe_id, Int, 0); + INIT_SINGLE(lastConfigIns, tableModel, Owner_id, Int, 0); + INIT_SINGLE(lastConfigIns, tableModel, Preset_id, Int, 0); + INIT_SINGLE(lastConfigIns, tableModel, ProbePortIndex, Int, 0); + } + + lastConfig = lastConfigIns; + + return ret; + } + + static bool selectFromLastConfig(QSqlTableModel* tableModel, QString filter = "") + { + tableModel->clear(); + tableModel->setTable("LastConfig"); + if(!filter.isEmpty()) + { + tableModel->setFilter(filter); + } + bool ret = tableModel->select(); + + return ret; + } + + static bool updateExistLastConfig(QSqlTableModel* tableModel, DbmDtoLastConfig& lastConfig) + { + tableModel->setData(tableModel->index(0, 1), lastConfig.Probe_id); + tableModel->setData(tableModel->index(0, 2), lastConfig.Application_id); + tableModel->setData(tableModel->index(0, 3), lastConfig.Preset_id); + tableModel->setData(tableModel->index(0, 4), lastConfig.ProbePortIndex); + tableModel->setData(tableModel->index(0, 5), 1); + + bool ret = tableModel->submit(); + + return ret; + } + + static bool setLastConfig(QSqlTableModel* tableModel, DbmDtoLastConfig& lastConfig) + { + auto filter = GET_MAX_ID_FILTER; + bool ret = selectFromLastConfig(tableModel, filter); + + if(tableModel->rowCount() > 0) + { + ret = updateExistLastConfig(tableModel, lastConfig); + } + else + { + QSqlRecord newRec = createLastConfigRecord(lastConfig); + ret = tableModel->insertRecord(-1, newRec); + } + + return ret; + } + + static QSqlRecord createLastConfigRecord(DbmDtoLastConfig& lastConfig) + { + QSqlRecord newRec; + + QSqlField probeId("Probe_id", QVariant::Int); + probeId.setValue(lastConfig.Probe_id); + + QSqlField applicationId("Application_id", QVariant::Int); + applicationId.setValue(lastConfig.Application_id); + + QSqlField presetId("Preset_id", QVariant::Int); + presetId.setValue(lastConfig.Preset_id); + + QSqlField probePortIndex("ProbePortIndex", QVariant::Int); + probePortIndex.setValue(lastConfig.ProbePortIndex); + + QSqlField ownerId("Owner_id", QVariant::Int); + ownerId.setValue(lastConfig.Owner_id); + + newRec.append(probeId); + newRec.append(applicationId); + newRec.append(presetId); + newRec.append(probePortIndex); + newRec.append(ownerId); + + return newRec; + } +}; + +#endif //DBMLASTCONFIG_H diff --git a/include/model/databaseManager/dto/ProbeProperties/DbmPreset.h b/include/model/databaseManager/dto/ProbeProperties/DbmPreset.h new file mode 100644 index 0000000..9e9296e --- /dev/null +++ b/include/model/databaseManager/dto/ProbeProperties/DbmPreset.h @@ -0,0 +1,67 @@ +#ifndef DBMPRESET_H +#define DBMPRESET_H + +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" +/*************************************************************************************************/ +/** + * @brief Database dto dtructure for Preset + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +typedef struct DbmDtoPreset +{ + int ID; + int Application_id; + int orderNum; + int Owner_id; + QString name; + QString showText; + QString abbreviation; +}DtoPreset; + +Q_DECLARE_METATYPE(DbmDtoPreset) + +/*************************************************************************************************/ +/** + * @brief Database class for Preset + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +class DbmPreset +{ +public: + static bool getPresetsByApplicationId(QString ID, + QSqlTableModel* tableModel, + QList& presets) + { + tableModel->setTable("Preset"); + tableModel->setFilter(QString("Application_id = '%1'").arg(ID)); + bool ret = tableModel->select(); + DbmDtoPreset presetIns; + for(int i = 0; i < tableModel->rowCount(); ++i) + { + INIT_SINGLE(presetIns, tableModel, ID, Int, i); + INIT_SINGLE(presetIns, tableModel, Application_id, Int, i); + INIT_SINGLE(presetIns, tableModel, orderNum, Int, i); + INIT_SINGLE(presetIns, tableModel, Owner_id, Int, i); + INIT_SINGLE(presetIns, tableModel, name, String, i); + INIT_SINGLE(presetIns, tableModel, showText, String, i); + INIT_SINGLE(presetIns, tableModel, abbreviation, String, i); + presets.append(presetIns); + } + + return ret; + } +}; + +#endif //DBMPRESET_H diff --git a/include/model/databaseManager/dto/ProbeProperties/DbmPresetValue.h b/include/model/databaseManager/dto/ProbeProperties/DbmPresetValue.h new file mode 100644 index 0000000..52af5dc --- /dev/null +++ b/include/model/databaseManager/dto/ProbeProperties/DbmPresetValue.h @@ -0,0 +1,122 @@ +#ifndef DBMPRESETVALUE_H +#define DBMPRESETVALUE_H + +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" +/*************************************************************************************************/ +/** + * @brief Database dto dtructure for Preset + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +typedef struct DbmDtoPresetValue +{ + int ID; + int angle; + int apcTxPower; + int criFilter; + int depth; + int dynContB; + int mla; + int stb; + int lineDensity; + double readZoom; + int rejectB; + int framFilter; + int lineFilter; + int criLineFilter; + int cri; + int enhanceB; + int gainB; + int focusNumber; + int persist; + int focus; + int tintMapB; + int grayMapB; + bool sriBypass; + int sri; + int oti; + bool xl; + int frequency; + bool hi; + bool ffc; + bool virtualConvex; + bool criBypass; + bool mirrorLR; + bool mirrorUD; + bool twoDSri; + int imageX; + int imageY; + int tgc; +}DtoPresetValue; + +Q_DECLARE_METATYPE(DbmDtoPresetValue) + +/*************************************************************************************************/ +/** + * @brief Database class for Preset + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +class DbmPresetValue +{ +public: + static bool getPresetValues(QString ID, + QSqlTableModel* tableModel, + DtoPresetValue& preset) + { + tableModel->setTable("PresetValue"); + tableModel->setFilter(QString("Preset_id = '%1'").arg(ID)); + bool ret = tableModel->select(); + INIT_SINGLE(preset, tableModel, ID, Int, 0); + INIT_SINGLE(preset, tableModel, angle, Int, 0); + INIT_SINGLE(preset, tableModel, apcTxPower, Int, 0); + INIT_SINGLE(preset, tableModel, criFilter, Int, 0); + INIT_SINGLE(preset, tableModel, depth, Int, 0); + INIT_SINGLE(preset, tableModel, dynContB, Int, 0); + INIT_SINGLE(preset, tableModel, mla, Int, 0); + INIT_SINGLE(preset, tableModel, stb, Int, 0); + INIT_SINGLE(preset, tableModel, lineDensity, Int, 0); + INIT_SINGLE(preset, tableModel, readZoom, Double, 0); + INIT_SINGLE(preset, tableModel, rejectB, Int, 0); + INIT_SINGLE(preset, tableModel, framFilter, Int, 0); + INIT_SINGLE(preset, tableModel, lineFilter, Int, 0); + INIT_SINGLE(preset, tableModel, criLineFilter, Int, 0); + INIT_SINGLE(preset, tableModel, cri, Int, 0); + INIT_SINGLE(preset, tableModel, enhanceB, Int, 0); + INIT_SINGLE(preset, tableModel, gainB, Int, 0); + INIT_SINGLE(preset, tableModel, focusNumber, Int, 0); + INIT_SINGLE(preset, tableModel, persist, Int, 0); + INIT_SINGLE(preset, tableModel, focus, Int, 0); + INIT_SINGLE(preset, tableModel, tintMapB, Int, 0); + INIT_SINGLE(preset, tableModel, grayMapB, Int, 0); + INIT_SINGLE(preset, tableModel, sriBypass, Bool, 0); + INIT_SINGLE(preset, tableModel, sri, Int, 0); + INIT_SINGLE(preset, tableModel, oti, Int, 0); + INIT_SINGLE(preset, tableModel, xl, Bool, 0); + INIT_SINGLE(preset, tableModel, frequency, Int, 0); + INIT_SINGLE(preset, tableModel, hi, Bool, 0); + INIT_SINGLE(preset, tableModel, ffc, Bool, 0); + INIT_SINGLE(preset, tableModel, virtualConvex, Bool, 0); + INIT_SINGLE(preset, tableModel, criBypass, Bool, 0); + INIT_SINGLE(preset, tableModel, mirrorLR, Bool, 0); + INIT_SINGLE(preset, tableModel, mirrorUD, Bool, 0); + INIT_SINGLE(preset, tableModel, twoDSri, Bool, 0); + INIT_SINGLE(preset, tableModel, imageX, Int, 0); + INIT_SINGLE(preset, tableModel, imageY, Int, 0); + INIT_SINGLE(preset, tableModel, tgc, Int, 0); + + return ret; + } +}; + +#endif //DBMPRESETVALUE_H diff --git a/include/model/databaseManager/dto/ProbeProperties/DbmProbeProperties.h b/include/model/databaseManager/dto/ProbeProperties/DbmProbeProperties.h new file mode 100644 index 0000000..58850a1 --- /dev/null +++ b/include/model/databaseManager/dto/ProbeProperties/DbmProbeProperties.h @@ -0,0 +1,225 @@ +#ifndef DBMPROBEPROPERTIES_H +#define DBMPROBEPROPERTIES_H + +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" + +/*************************************************************************************************/ +/** + * @brief Database dto dtructure for Probe properties + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +typedef struct DbmDtoProbeProperties +{ +public: + int ID; + QString globalId; + QString name; + QString image; + bool scan; + int type; + bool geometry; + QList supportedModes; + double pitch; + double radius; + int subAzimuthNo; + int subElevationNo; + int elementNo; + double elementWidth; + double elementHeight; + double fov; + QList impulseResponse; + QList angleValues; + QList focusValues; + QList hiFocusValues; + int multiFocusStep; + QList otiC0Values; + QList > ffcValues; + QList depthValues; + QList frequencyValues; + QList hiFrequencyValues; + QList dFrequencyValues; + QList pwFrequencyValues; + QList > criSteeringAngles; + double rxGain; + double txGain; + QList lineDensityValues; + QList dLineDensityValues; + int halfCycleNoValues; + int ffcHalfCycleNoValues; + QList hiHalfCycleNoValues; + QList dopplerHalfCycleNoValues; + QList priExtensionValue; + double dPriExtensionValue; + double txResolution; + double rxResolution; + double mLinesPri; + int simultPwFrameRate; + QList virtualConvexLineDensityValues; + double vcMaxTheta; + QList piValues; + QList hiNames; + QList AtgcB; + QList AtgcD; + QList AtgcPW; + QList AtgcReserve; +}DbmDtoProbeProperties; + +Q_DECLARE_METATYPE(DbmDtoProbeProperties) + +/*************************************************************************************************/ +/** + * @brief Database class for Probe properties + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +class DbmProbeProperties +{ +public: + static bool getProbeParameters(QSqlTableModel* tableModel, QList& probes) + { + tableModel->setTable("Probe"); + bool ret = tableModel->select(); + DbmDtoProbeProperties probeIns; + for(int i = 0; i < tableModel->rowCount(); ++i) + { + INIT_SINGLE(probeIns, tableModel, ID, Int, i); + INIT_SINGLE(probeIns, tableModel, globalId, String, i); + INIT_SINGLE(probeIns, tableModel, image, String, i); + INIT_SINGLE(probeIns, tableModel, name, String, i); + INIT_SINGLE(probeIns, tableModel, scan, Bool, i); + INIT_SINGLE(probeIns, tableModel, type, Int, i); + INIT_SINGLE(probeIns, tableModel, geometry, Bool, i); + INIT_SINGLE(probeIns, tableModel, pitch, Double, i); + INIT_SINGLE(probeIns, tableModel, radius, Double, i); + INIT_SINGLE(probeIns, tableModel, subAzimuthNo, Int, i); + INIT_SINGLE(probeIns, tableModel, subElevationNo, Int, i); + INIT_SINGLE(probeIns, tableModel, elementNo, Int, i); + INIT_SINGLE(probeIns, tableModel, elementHeight, Double, i); + INIT_SINGLE(probeIns, tableModel, elementWidth, Double, i); + INIT_SINGLE(probeIns, tableModel, fov, Double, i); + INIT_SINGLE(probeIns, tableModel, multiFocusStep, Int, i); + INIT_SINGLE(probeIns, tableModel, rxGain, Double, i); + INIT_SINGLE(probeIns, tableModel, txGain, Double, i); + INIT_SINGLE(probeIns, tableModel, halfCycleNoValues, Int, i); + INIT_SINGLE(probeIns, tableModel, ffcHalfCycleNoValues, Int, i); + INIT_SINGLE(probeIns, tableModel, dPriExtensionValue, Int, i); + INIT_SINGLE(probeIns, tableModel, txResolution, Double, i); + INIT_SINGLE(probeIns, tableModel, rxResolution, Double, i); + INIT_SINGLE(probeIns, tableModel, mLinesPri, Double, i); + INIT_SINGLE(probeIns, tableModel, simultPwFrameRate, Int, i); + INIT_SINGLE(probeIns, tableModel, vcMaxTheta, Double, i); + INIT_LIST(probeIns, tableModel, virtualConvexLineDensityValues, Double, i); + INIT_LIST(probeIns, tableModel, impulseResponse, Double, i); + INIT_LIST(probeIns, tableModel, hiFocusValues, Double, i); + INIT_LIST(probeIns, tableModel, supportedModes, Int, i); + INIT_LIST(probeIns, tableModel, angleValues, Int, i); + INIT_LIST(probeIns, tableModel, focusValues, Double, i); + INIT_LIST(probeIns, tableModel, depthValues, Double, i); + INIT_LIST(probeIns, tableModel, frequencyValues, Int, i); + INIT_LIST(probeIns, tableModel, otiC0Values, Int, i); + INIT_LIST(probeIns, tableModel, hiFrequencyValues, Int, i); + INIT_LIST(probeIns, tableModel, dFrequencyValues, Int, i); + INIT_LIST(probeIns, tableModel, lineDensityValues, Double, i); + INIT_LIST(probeIns, tableModel, dLineDensityValues, Double, i); + INIT_LIST(probeIns, tableModel, hiHalfCycleNoValues, Int, i); + INIT_LIST(probeIns, tableModel, dopplerHalfCycleNoValues, Int, i); + INIT_LIST(probeIns, tableModel, priExtensionValue, Double, i); + INIT_LIST(probeIns, tableModel, piValues, Int, i); + INIT_LIST(probeIns, tableModel, pwFrequencyValues, Int, i); + INIT_LIST(probeIns, tableModel, AtgcB, Double, i); + INIT_LIST(probeIns, tableModel, AtgcD, Double, i); + INIT_LIST(probeIns, tableModel, AtgcPW, Double, i); + INIT_LIST(probeIns, tableModel, AtgcReserve, Double, i); + INIT_LIST_STR(probeIns, tableModel, hiNames, i); + INTI_LIST_LIST(probeIns, tableModel, ffcValues, double, Double, i); + INTI_LIST_LIST(probeIns, tableModel, criSteeringAngles, double, Double, i); + probes.append(probeIns); + } + + return ret; + } + + /*************************************************************************************************/ + /** + * @brief Get a Prob properties by Global Id. + * @details + * @return bool + */ + /*************************************************************************************************/ + static bool getProbeParametersByGlobalId(QString name, + QSqlTableModel* tableModel, + DbmDtoProbeProperties& probe) + { + tableModel->setTable("Probe"); + tableModel->setFilter(QString("globalId is '%1'").arg(name)); + bool ret = tableModel->select(); + + qDebug() << tableModel->rowCount(); + INIT_SINGLE(probe, tableModel, ID, Int, 0); + INIT_SINGLE(probe, tableModel, globalId, String, 0); + INIT_SINGLE(probe, tableModel, image, String, 0); + INIT_SINGLE(probe, tableModel, name, String, 0); + INIT_SINGLE(probe, tableModel, scan, Bool, 0); + INIT_SINGLE(probe, tableModel, type, Int, 0); + INIT_SINGLE(probe, tableModel, geometry, Bool, 0); + INIT_SINGLE(probe, tableModel, pitch, Double, 0); + INIT_SINGLE(probe, tableModel, radius, Double, 0); + INIT_SINGLE(probe, tableModel, subAzimuthNo, Int, 0); + INIT_SINGLE(probe, tableModel, subElevationNo, Int, 0); + INIT_SINGLE(probe, tableModel, elementNo, Int, 0); + INIT_SINGLE(probe, tableModel, elementHeight, Double, 0); + INIT_SINGLE(probe, tableModel, elementWidth, Double, 0); + INIT_SINGLE(probe, tableModel, fov, Double, 0); + INIT_SINGLE(probe, tableModel, multiFocusStep, Int, 0); + INIT_SINGLE(probe, tableModel, rxGain, Double, 0); + INIT_SINGLE(probe, tableModel, txGain, Double, 0); + INIT_SINGLE(probe, tableModel, halfCycleNoValues, Int, 0); + INIT_SINGLE(probe, tableModel, ffcHalfCycleNoValues, Int, 0); + INIT_SINGLE(probe, tableModel, dPriExtensionValue, Int, 0); + INIT_SINGLE(probe, tableModel, txResolution, Double, 0); + INIT_SINGLE(probe, tableModel, rxResolution, Double, 0); + INIT_SINGLE(probe, tableModel, mLinesPri, Double, 0); + INIT_SINGLE(probe, tableModel, simultPwFrameRate, Int, 0); + INIT_SINGLE(probe, tableModel, vcMaxTheta, Double, 0); + INIT_LIST(probe, tableModel, virtualConvexLineDensityValues, Double, 0); + INIT_LIST(probe, tableModel, impulseResponse, Double, 0); + INIT_LIST(probe, tableModel, hiFocusValues, Double, 0); + INIT_LIST(probe, tableModel, supportedModes, Int, 0); + INIT_LIST(probe, tableModel, angleValues, Int, 0); + INIT_LIST(probe, tableModel, focusValues, Double, 0); + INIT_LIST(probe, tableModel, depthValues, Double, 0); + INIT_LIST(probe, tableModel, frequencyValues, Int, 0); + INIT_LIST(probe, tableModel, otiC0Values, Int, 0); + INIT_LIST(probe, tableModel, hiFrequencyValues, Int, 0); + INIT_LIST(probe, tableModel, dFrequencyValues, Int, 0); + INIT_LIST(probe, tableModel, lineDensityValues, Double, 0); + INIT_LIST(probe, tableModel, dLineDensityValues, Double, 0); + INIT_LIST(probe, tableModel, hiHalfCycleNoValues, Int, 0); + INIT_LIST(probe, tableModel, dopplerHalfCycleNoValues, Int, 0); + INIT_LIST(probe, tableModel, priExtensionValue, Double, 0); + INIT_LIST(probe, tableModel, piValues, Int, 0); + INIT_LIST(probe, tableModel, pwFrequencyValues, Int, 0); + INIT_LIST(probe, tableModel, AtgcB, Double, 0); + INIT_LIST(probe, tableModel, AtgcD, Double, 0); + INIT_LIST(probe, tableModel, AtgcPW, Double, 0); + INIT_LIST(probe, tableModel, AtgcReserve, Double, 0); + INIT_LIST_STR(probe, tableModel, hiNames, 0); + INTI_LIST_LIST(probe, tableModel, ffcValues, double, Double, 0); + INTI_LIST_LIST(probe, tableModel, criSteeringAngles, double, Double, 0); + + return ret; + } +}; + +#endif //DBMPROBEPROPERTIES_H diff --git a/include/model/databaseManager/dto/System/DbmCriFilter.h b/include/model/databaseManager/dto/System/DbmCriFilter.h new file mode 100644 index 0000000..33be138 --- /dev/null +++ b/include/model/databaseManager/dto/System/DbmCriFilter.h @@ -0,0 +1,50 @@ +#ifndef DBMCRIFILTER_H +#define DBMCRIFILTER_H + +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" + +/*************************************************************************************************/ +/** + * @brief database dto structure for CRI filter + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +typedef struct DbmDtoCriFilter +{ + QList zeroSteeringFrameWeight; + bool isActive; +}DtoCrDbmDtoCriFilteriFilter; + +Q_DECLARE_METATYPE(DbmDtoCriFilter) + +/*************************************************************************************************/ +/** + * @brief database class for CRI filter + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +class DbmCriFilter +{ +public: + static bool getCriFilter(QSqlTableModel* tableModel, DbmDtoCriFilter& criFilter) + { + tableModel->setTable("CriFilter"); + tableModel->setFilter(QString("isActive = 1")); + bool ret = tableModel->select(); + INIT_LIST(criFilter, tableModel, zeroSteeringFrameWeight, Int, 0); + + return ret; + } +}; + +#endif //DBMCRIFILTER_H diff --git a/include/model/databaseManager/dto/System/DbmDynamicContrast.h b/include/model/databaseManager/dto/System/DbmDynamicContrast.h new file mode 100644 index 0000000..23c0e3d --- /dev/null +++ b/include/model/databaseManager/dto/System/DbmDynamicContrast.h @@ -0,0 +1,51 @@ +#ifndef DBMDYNAMICCONTRAST_H +#define DBMDYNAMICCONTRAST_H + +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" + +/*************************************************************************************************/ +/** + * @brief Database dto structure for Dynamic contrast. + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +typedef struct DbmDtoDynamicContrast +{ + QList gamma; + bool isActive; +}DbmDtoDynamicContrast; + +Q_DECLARE_METATYPE(DbmDtoDynamicContrast) + +/*************************************************************************************************/ +/** + * @brief Database class for Dynamic contrast. + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +class DbmDynamicContrast +{ +public: + static bool getDynamicContrast(QSqlTableModel* tableModel, + DbmDtoDynamicContrast& dynamicContrast) + { + tableModel->setTable("DynamicContrast"); + tableModel->setFilter(QString("isActive = 1")); + bool ret = tableModel->select(); + INIT_LIST(dynamicContrast, tableModel, gamma, Double, 0); + + return ret; + } +}; + +#endif //DBMDYNAMICCONTRAST_H diff --git a/include/model/databaseManager/dto/System/DbmEnhance.h b/include/model/databaseManager/dto/System/DbmEnhance.h new file mode 100644 index 0000000..0552d82 --- /dev/null +++ b/include/model/databaseManager/dto/System/DbmEnhance.h @@ -0,0 +1,54 @@ +#ifndef ENHANCE_H +#define ENHANCE_H + +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" + +/*************************************************************************************************/ +/** + * @brief Database dto dtructure for Enhance + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +typedef struct DbmDtoEnhance +{ + QList alpha; + QList sigma; + int logFilterSize; + bool isActive; +}DbmDtoEnhance; + +Q_DECLARE_METATYPE(DbmDtoEnhance) + +/*************************************************************************************************/ +/** + * @brief Database Class for Enhance + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +class DbmEnhance +{ +public: + static bool getEnhance(QSqlTableModel* tableModel, DbmDtoEnhance& enhance) + { + tableModel->setTable("Enhance"); + tableModel->setFilter(QString("isActive = 1")); + bool ret = tableModel->select(); + INIT_SINGLE(enhance, tableModel, logFilterSize, Int, 0); + INIT_LIST(enhance, tableModel, sigma, Double, 0); + INIT_LIST(enhance, tableModel, alpha, Double, 0); + + return ret; + } +}; + +#endif //ENHANCE_H diff --git a/include/model/databaseManager/dto/System/DbmGrayMap.h b/include/model/databaseManager/dto/System/DbmGrayMap.h new file mode 100644 index 0000000..d7cabc3 --- /dev/null +++ b/include/model/databaseManager/dto/System/DbmGrayMap.h @@ -0,0 +1,63 @@ +#ifndef DBMGRAYMAP_H +#define DBMGRAYMAP_H + +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" + +#define GRAYMAP_COUNT 18 +/*************************************************************************************************/ +/** + * @brief Database dto structu for Graymap + * @author MMT + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +typedef struct DbmDtoGrayMap +{ + QList > grayMapData; + bool isActive; +}DbmDtoGrayMap; + +Q_DECLARE_METATYPE(DbmDtoGrayMap) + +/*************************************************************************************************/ +/** + * @brief Database class for Graymap + * @author MMT + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +class DbmGrayMap +{ +public: + static bool getGrayMap(QSqlTableModel* tableModel, DbmDtoGrayMap& grayMap) + { + tableModel->setTable("GrayMap"); + tableModel->setFilter(QString("isActive = 1")); + bool ret = tableModel->select(); + for(int i = 0; i < GRAYMAP_COUNT; ++i) + { + auto __grayMapData = + tableModel->record(0).value("DATA" + QString::number(i + 1)).toString().split(',', + QString::SkipEmptyParts); + QList temp; + for(int j = 0; j < __grayMapData.length(); ++j) + { + temp.append(__grayMapData[j].toInt()); + } + grayMap.grayMapData.append(temp); + temp.clear(); + } + + return ret; + } +}; + +#endif //DBMGRAYMAP_H diff --git a/include/model/databaseManager/dto/System/DbmSri.h b/include/model/databaseManager/dto/System/DbmSri.h new file mode 100644 index 0000000..6c12340 --- /dev/null +++ b/include/model/databaseManager/dto/System/DbmSri.h @@ -0,0 +1,52 @@ +#ifndef DBMSRI_H +#define DBMSRI_H + +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" + +/*************************************************************************************************/ +/** + * @brief Database dto structure for SRI + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +typedef struct DbmDtoSri +{ + QList alpha; + QList windowSize; + bool isActive; +}DbmDtoSri; + +Q_DECLARE_METATYPE(DbmDtoSri) + +/*************************************************************************************************/ +/** + * @brief Database class for SRI + * @author Mohammad Mohsen Talaie + * @details + * @date 2020 + */ +/*************************************************************************************************/ +class DbmSri +{ +public: + static bool getSri(QSqlTableModel* tableModel, DbmDtoSri& sri) + { + tableModel->setTable("Sri"); + tableModel->setFilter(QString("isActive = 1")); + bool ret = tableModel->select(); + INIT_LIST(sri, tableModel, alpha, Double, 0); + INIT_LIST(sri, tableModel, windowSize, Int, 0); + + return ret; + } +}; + +#endif //DBMSRI_H diff --git a/include/model/databaseManager/dto/System/DbmSysParameters.h b/include/model/databaseManager/dto/System/DbmSysParameters.h new file mode 100644 index 0000000..0e6dcd8 --- /dev/null +++ b/include/model/databaseManager/dto/System/DbmSysParameters.h @@ -0,0 +1,120 @@ +#ifndef DBMSYSPARAMETERS_H +#define DBMSYSPARAMETERS_H + +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" +#include "model/databaseManager/type/EAlgorithmType.h" + +/*************************************************************************************************/ +/** + * @brief Database dto structure for System parameters. + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +typedef struct DbmDtoSysParameters +{ +public: + bool quantizerEnable; + bool computeInteger; + int mla; + int dopplerMla; + int stb; + int dopplerStb; + int apodization; + int adcClock; + int apoTableSize; + int apoBitNo; + int pwFftPointNo; + int tx2rxGuardTime; + double lineDt; + double delayCalcDt; + double fpgaTxDt; + double dt; + double startDepth; + double maxX; + double maxY; + double maxZ; + double pwLineInterval; + double dcCancelR; + QString beamFormer; + EAlgorithmType::eEnhanceAlgorithmType enhanceAlgorithm; + EAlgorithmType::eSriAlgorithmType sriAlgorithm; + EAlgorithmType::epwFftWinNameType pwFftWinName; + QList wmfFc; + QList ipfLut; + QList bannedF0; +}DbmDtoSysParameters; + +Q_DECLARE_METATYPE(DbmDtoSysParameters) + +/*************************************************************************************************/ +/** + * @brief Database class for System paramenters + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +class DbmSysParameters +{ +public: + static bool getSysParameters(QSqlTableModel* tableModel, DbmDtoSysParameters& SysParameters) + { + tableModel->setTable("SysParameters"); + tableModel->setFilter(QString("isActive = 1")); + bool ret = tableModel->select(); + INIT_SINGLE(SysParameters, tableModel, mla, Int, 0); + INIT_SINGLE(SysParameters, tableModel, dopplerMla, Int, 0); + INIT_SINGLE(SysParameters, tableModel, stb, Int, 0); + INIT_SINGLE(SysParameters, tableModel, dopplerStb, Int, 0); + INIT_SINGLE(SysParameters, tableModel, apodization, Int, 0); + INIT_SINGLE(SysParameters, tableModel, quantizerEnable, Bool, 0); + INIT_SINGLE(SysParameters, tableModel, computeInteger, Bool, 0); + INIT_SINGLE(SysParameters, tableModel, adcClock, Int, 0); + INIT_SINGLE(SysParameters, tableModel, apoTableSize, Int, 0); + INIT_SINGLE(SysParameters, tableModel, apoBitNo, Int, 0); + INIT_SINGLE(SysParameters, tableModel, pwFftPointNo, Int, 0); + INIT_SINGLE(SysParameters, tableModel, tx2rxGuardTime, Int, 0); + INIT_SINGLE(SysParameters, tableModel, lineDt, Double, 0); + INIT_SINGLE(SysParameters, tableModel, delayCalcDt, Double, 0); + INIT_SINGLE(SysParameters, tableModel, fpgaTxDt, Double, 0); + INIT_SINGLE(SysParameters, tableModel, dt, Double, 0); + INIT_SINGLE(SysParameters, tableModel, startDepth, Double, 0); + INIT_SINGLE(SysParameters, tableModel, maxX, Double, 0); + INIT_SINGLE(SysParameters, tableModel, maxY, Double, 0); + INIT_SINGLE(SysParameters, tableModel, maxZ, Double, 0); + INIT_SINGLE(SysParameters, tableModel, pwLineInterval, Double, 0); + INIT_SINGLE(SysParameters, tableModel, dcCancelR, Double, 0); + INIT_SINGLE(SysParameters, tableModel, beamFormer, String, 0); + INIT_SINGLE_STR_TO_ENUM(SysParameters, + tableModel, + enhanceAlgorithm, + EAlgorithmType::convertEnhanceAlgorithmToEnum, + 0); + + INIT_SINGLE_STR_TO_ENUM(SysParameters, + tableModel, + sriAlgorithm, + EAlgorithmType::convertSriAlgorithmToEnum, + 0); + INIT_SINGLE_STR_TO_ENUM(SysParameters, + tableModel, + pwFftWinName, + EAlgorithmType::convertPwFftWinToEnum, + 0); + INIT_LIST(SysParameters, tableModel, wmfFc, Double, 0); + INIT_LIST(SysParameters, tableModel, ipfLut, Double, 0); + INIT_LIST(SysParameters, tableModel, bannedF0, Double, 0); + + return ret; + } +}; + +#endif //DBMSYSPARAMETERS_H diff --git a/include/model/databaseManager/dto/System/DbmTgc.h b/include/model/databaseManager/dto/System/DbmTgc.h new file mode 100644 index 0000000..e09cc2f --- /dev/null +++ b/include/model/databaseManager/dto/System/DbmTgc.h @@ -0,0 +1,63 @@ +#ifndef DBMTGC_H +#define DBMTGC_H + +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" + +#define TGC_COUNT 9 +/*************************************************************************************************/ +/** + * @brief Database dto structu for Graymap + * @author MMT + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +typedef struct DbmDtoTgc +{ + QList > tgcData; + bool isActive; +}DbmDtoTgc; + +Q_DECLARE_METATYPE(DbmDtoTgc) + +/*************************************************************************************************/ +/** + * @brief Database class for Graymap + * @author MMT + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +class DbmTgc +{ +public: + static bool getTgc(QSqlTableModel* tableModel, DbmDtoTgc& tgc) + { + tableModel->setTable("Tgc"); + tableModel->setFilter(QString("isActive = 1")); + bool ret = tableModel->select(); + for(int i = 0; i < TGC_COUNT; ++i) + { + auto tgcData = + tableModel->record(0).value("data" + QString::number(i + 1)).toString().split(',', + QString::SkipEmptyParts); + QList temp; + for(int j = 0; j < tgcData.length(); ++j) + { + temp.append(tgcData[j].toInt()); + } + tgc.tgcData.append(temp); + temp.clear(); + } + + return ret; + } +}; + +#endif //DBMTGC_H diff --git a/include/model/databaseManager/dto/System/DbmTintMap.h b/include/model/databaseManager/dto/System/DbmTintMap.h new file mode 100644 index 0000000..1f1c2e8 --- /dev/null +++ b/include/model/databaseManager/dto/System/DbmTintMap.h @@ -0,0 +1,73 @@ +#ifndef DBMTINTMAP_H +#define DBMTINTMAP_H + +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" +#include "model/databaseManager/type/ETintMapName.h" + +/*************************************************************************************************/ +/** + * @brief Database dto structure for Tintmap + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +typedef struct DbmDtoTintMap +{ + QString name; + QList > value; + bool isActive; + int inOrder; +}DbmDtoTintMap; + +Q_DECLARE_METATYPE(DbmDtoTintMap) + +/*************************************************************************************************/ +/** + * @brief Database class for Tintmap. + * @author Mohammad Mohsen Talaie + * @details + * @date 20 sep 2020 + */ +/*************************************************************************************************/ +class DbmTintMap +{ +public: + static bool getAllTintMap(QSqlTableModel* tableModel, QList& tintMaps) + { + tableModel->setTable("TintMap"); + tableModel->setFilter(QString("isActive is true")); + bool ret = tableModel->select(); + int a = tableModel->rowCount(); + for(int i = 0; i < tableModel->rowCount(); ++i) + { + DbmDtoTintMap tintMapIns; + INIT_SINGLE(tintMapIns, tableModel, name, String, i); + INTI_LIST_LIST(tintMapIns, tableModel, value, int, Int, i); + INIT_SINGLE(tintMapIns, tableModel, inOrder, Int, i); + tintMaps.append(tintMapIns); + } + + return ret; + } + + static bool getTintMapByName(QString name, QSqlTableModel* tableModel, DbmDtoTintMap& tintMap) + { + tableModel->setTable("TintMap"); + tableModel->setFilter(QString("isActive = 1 and name is '%1'").arg(name)); + bool ret = tableModel->select(); + INIT_SINGLE(tintMap, tableModel, name, String, 0); + INTI_LIST_LIST(tintMap, tableModel, value, int, Int, 0); + INIT_SINGLE(tintMap, tableModel, inOrder, Int, 0); + + return ret; + } +}; + +#endif //DBMTINTMAP_H diff --git a/include/model/databaseManager/dto/User/DbmUser.h b/include/model/databaseManager/dto/User/DbmUser.h new file mode 100644 index 0000000..78d6a47 --- /dev/null +++ b/include/model/databaseManager/dto/User/DbmUser.h @@ -0,0 +1,79 @@ +#ifndef DBMUSER_H +#define DBMUSER_H + +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" + +/*************************************************************************************************/ +/** + * @brief Database dto structure for User + * @author Mohammad Mohsen Talaie + * @details + * @date 21 feb 2021 + */ +/*************************************************************************************************/ +typedef struct DbmDtoUser +{ + int ID; + QString name; + QString family; + QString username; + QString password; +}DbmDtoUser; + +Q_DECLARE_METATYPE(DbmDtoUser) + +/*************************************************************************************************/ +/** + * @brief Database class for User + * @author Mohammad Mohsen Talaie + * @details + * @date 21 feb 2021 + */ +/*************************************************************************************************/ +class DbmUser +{ +public: + static bool getUsers(QSqlTableModel* tableModel, QList& users) + { + tableModel->setTable("User"); + bool ret = tableModel->select(); + DbmDtoUser userIns; + + for(int i = 0; i < tableModel->rowCount(); ++i) + { + if(tableModel->record(i).value("ID").toInt() > 0) + { + INIT_SINGLE(userIns, tableModel, ID, Int, i); + INIT_SINGLE(userIns, tableModel, name, String, i); + INIT_SINGLE(userIns, tableModel, family, String, i); + INIT_SINGLE(userIns, tableModel, username, String, i); + INIT_SINGLE(userIns, tableModel, password, String, i); + users.append(userIns); + } + } + + return ret; + } + + static bool getUserByUsername(QString username, QSqlTableModel* tableModel, DbmDtoUser& user) + { + tableModel->setTable("User"); + tableModel->setFilter(QString("Username is '%1'").arg(username)); + bool ret = tableModel->select(); + INIT_SINGLE(user, tableModel, ID, Int, 0); + INIT_SINGLE(user, tableModel, name, String, 0); + INIT_SINGLE(user, tableModel, family, String, 0); + INIT_SINGLE(user, tableModel, username, String, 0); + INIT_SINGLE(user, tableModel, password, String, 0); + + return ret; + } +}; + +#endif //DBMUSER_H diff --git a/include/model/databaseManager/dto/User/DbmUserGrayMap.h b/include/model/databaseManager/dto/User/DbmUserGrayMap.h new file mode 100644 index 0000000..5ad1170 --- /dev/null +++ b/include/model/databaseManager/dto/User/DbmUserGrayMap.h @@ -0,0 +1,298 @@ +#ifndef USERGRAYMAP_H +#define USERGRAYMAP_H + +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" +#include "model/databaseManager/utils/StaticUtility.h" + +#define GRAYMAP_COUNT 21 +#define FACTORY "factory" +/*************************************************************************************************/ +/** + * @brief Database dto structure for User + * @author Mohammad Mohsen Talaie + * @details + * @date 21 feb 2021 + */ +/*************************************************************************************************/ +typedef struct DbmDtoUserGrayMap +{ + int ID; + int User_Id; + QList > userGrayMapData; +}DbmDtoUserGrayMap; + +Q_DECLARE_METATYPE(DbmDtoUserGrayMap) + +/*************************************************************************************************/ +/** + * @brief Database class for User + * @author Mohammad Mohsen Talaie + * @details + * @date 21 feb 2021 + */ +/*************************************************************************************************/ +class DbmUserGrayMap +{ +private: + static int getUserIDByUsername(QString username, QSqlTableModel* tableModel) + { + tableModel->setTable("User"); + tableModel->setFilter(QString("username is '%1'").arg(username)); + bool ret = tableModel->select(); + if(ret) + { + int id = tableModel->record(0).value("ID").toInt(); + + return id; + } + + return 0; + } + + static QList pripareGrayMapList(QStringList _grayMapData) + { + QList dataTemp; + for(int k = 0; k < _grayMapData.length(); ++k) + { + dataTemp.append(_grayMapData[k].toInt()); + } + + return dataTemp; + } + + static QStringList getGrayMapListFromRow(QSqlTableModel* tableModel, + int rowNumber, + int dataNumber) + { + auto __grayMapData = + tableModel->record(rowNumber).value("DATA" + + QString::number(dataNumber)).toString().split(',', + QString::SkipEmptyParts); + + return __grayMapData; + } + + static QList > getGrayMapDataFromRow(int i, QSqlTableModel* tableModel) + { + QList > allData; + for(int j = 19; j <= GRAYMAP_COUNT; ++j) + { + auto __grayMapData = getGrayMapListFromRow(tableModel, i, j); + + QList dataTemp = pripareGrayMapList(__grayMapData); + + allData.append(dataTemp); + + dataTemp.clear(); + } + + return allData; + } + + static bool insertInitUserGrayMapFromFactory(int userId, + QSqlTableModel* tableModel) + { + DbmDtoUserGrayMap userGraymap; + getUserGrayMapByUsername(FACTORY, tableModel, userGraymap); + userGraymap.User_Id = userId; + tableModel->clear(); + + return setUserGrayMapByUserId(userId, tableModel, userGraymap); + } + + static QSqlRecord createUserGrayMapRecord(DbmDtoUserGrayMap& userGraymap) + { + QSqlRecord newRec; + QSqlField uId("User_id", QVariant::Int); + uId.setValue(userGraymap.User_Id); + QSqlField data19("data19", QVariant::String); + data19.setValue(StaticUtility::convertListToString(userGraymap.userGrayMapData.at(0))); + QSqlField data20("data20", QVariant::String); + data20.setValue(StaticUtility::convertListToString(userGraymap.userGrayMapData.at(1))); + QSqlField data21("data21", QVariant::String); + data21.setValue(StaticUtility::convertListToString(userGraymap.userGrayMapData.at(2))); + + newRec.append(uId); + newRec.append(data19); + newRec.append(data20); + newRec.append(data21); + + return newRec; + } + + static bool selectFromUserGrayMap(QSqlTableModel* tableModel, QString filter = "") + { + tableModel->setTable("UserGrayMap"); + if(!filter.isEmpty()) + { + tableModel->setFilter(filter); + } + + bool ret = tableModel->select(); + + return ret; + } + +public: + static bool getUserGrayMaps(QSqlTableModel* tableModel, QList& userGrayMaps) + { + bool ret = selectFromUserGrayMap(tableModel); + DbmDtoUserGrayMap userIns; + + for(int i = 0; i < tableModel->rowCount(); ++i) + { + if(tableModel->record(i).value("ID").toInt() > 0) + { + DbmDtoUserGrayMap gmTemp; + gmTemp.userGrayMapData.append(getGrayMapDataFromRow(i, tableModel)); + + gmTemp.ID = tableModel->record(i).value("ID").toInt(); + + gmTemp.User_Id = tableModel->record(i).value("User_Id").toInt(); + + userGrayMaps.append(gmTemp); + } + } + + return ret; + } + + static bool getUserGrayMapByUserId(int userId, + QSqlTableModel* tableModel, + DbmDtoUserGrayMap& userGraymap) + { + auto filter = QString("User_Id is %1").arg(userId); + bool ret = selectFromUserGrayMap(tableModel, filter); + + if(tableModel->rowCount() < 1) + { + insertInitUserGrayMapFromFactory(userId, tableModel); + ret = tableModel->select(); + if(!ret) + { + return false; + } + } + + userGraymap.userGrayMapData.append(getGrayMapDataFromRow(0, tableModel)); + + userGraymap.ID = tableModel->record(0).value("ID").toInt(); + + userGraymap.User_Id = tableModel->record(0).value("User_Id").toInt(); + + return ret; + } + + static bool getUserGrayMapByUsername(QString username, + QSqlTableModel* tableModel, + DbmDtoUserGrayMap& userGraymap) + { + tableModel->setTable("UserGrayMap"); + int userId = getUserIDByUsername(username, tableModel); + if(userId > 0) + { + auto ret = getUserGrayMapByUserId(userId, tableModel, userGraymap); + + return ret; + } + + return false; + } + + static bool setUserGrayMapByUserId(int userId, + QSqlTableModel* tableModel, + DbmDtoUserGrayMap& userGraymap) + { + bool ret; + auto filter = QString("User_Id is %1").arg(userId); + auto noError = selectFromUserGrayMap(tableModel, filter); + if(!noError) + { + return false; + } + if(tableModel->rowCount() > 0) + { + ret = tableModel->setData(tableModel->index(0, 1), 2); + QVariant data19; + data19.setValue(StaticUtility::convertListToString(userGraymap.userGrayMapData.at( + 0))); + ret = tableModel->setData(tableModel->index(0, 2), data19); + + QVariant data20; + data20.setValue(StaticUtility::convertListToString(userGraymap.userGrayMapData.at( + 0))); + ret = tableModel->setData(tableModel->index(0, 3), data20); + + QVariant data21; + data21.setValue(StaticUtility::convertListToString(userGraymap.userGrayMapData.at( + 0))); + ret = tableModel->setData(tableModel->index(0, 4), data21); + + ret = tableModel->submit(); + } + else + { + userGraymap.User_Id = userId; + QSqlRecord newRec = createUserGrayMapRecord(userGraymap); + ret = tableModel->insertRecord(-1, newRec); + } + + return ret; + } + + static bool setUserGrayMapByUsername(QString username, + QSqlTableModel* tableModel, + DbmDtoUserGrayMap& userGraymap) + { + bool ret; + int userId = getUserIDByUsername(username, tableModel); + if(userId == 0) + { + return false; + } + + return setUserGrayMapByUserId(userId, tableModel, userGraymap); + } + + static bool updateUserGrayMapFieldByUserId(QSqlTableModel* tableModel, + int userId, + int index, + QList grayMap) + { + auto filter = QString("User_Id is %1").arg(userId); + auto noError = selectFromUserGrayMap(tableModel, filter); + if(!noError) + { + return false; + } + int trueIndex = index + 2; //0 : id | 1 : User_Id + QVariant data; + data.setValue(StaticUtility::convertListToString(grayMap)); + bool ret = tableModel->setData(tableModel->index(0, trueIndex), data); + ret = tableModel->submit(); + + return ret; + } + + static bool updateUserGrayMapFieldByUsername(QSqlTableModel* tableModel, + QString username, + int index, + QList grayMap) + { + int userId = getUserIDByUsername(username, tableModel); + if(userId > 0) + { + return updateUserGrayMapFieldByUserId(tableModel, userId, index, grayMap); + } + + return false; + } +}; + +#endif //USERGRAYMAP_H diff --git a/include/model/databaseManager/dto/User/DbmUserTgc.h b/include/model/databaseManager/dto/User/DbmUserTgc.h new file mode 100644 index 0000000..ed70c43 --- /dev/null +++ b/include/model/databaseManager/dto/User/DbmUserTgc.h @@ -0,0 +1,295 @@ +#ifndef DBMUSERTGC_H +#define DBMUSERTGC_H +#include +#include +#include +#include +#include + +#include "model/databaseManager/utils/initializationUtils.h" +#include "model/databaseManager/utils/StaticUtility.h" + +#define TGC_COUNT 12 +#define FACTORY "factory" +/*************************************************************************************************/ +/** + * @brief Database dto structure for User + * @author Mohammad Mohsen Talaie + * @details + * @date 23 feb 2021 + */ +/*************************************************************************************************/ +typedef struct DbmDtoUserTgc +{ + int ID; + int User_Id; + QList > userTgcData; +}DbmDtoUserTgc; + +Q_DECLARE_METATYPE(DbmDtoUserTgc) + +/*************************************************************************************************/ +/** + * @brief Database class for User + * @author Mohammad Mohsen Talaie + * @details + * @date 23 feb 2021 + */ +/*************************************************************************************************/ +class DbmUserTgc +{ +private: + static int getUserIDByUsername(QString username, QSqlTableModel* tableModel) + { + tableModel->setTable("User"); + tableModel->setFilter(QString("username is '%1'").arg(username)); + bool ret = tableModel->select(); + if(ret) + { + int id = tableModel->record(0).value("ID").toInt(); + + return id; + } + + return 0; + } + + static QList pripareTgcList(QStringList tgcData) + { + QList dataTemp; + for(int k = 0; k < tgcData.length(); ++k) + { + dataTemp.append(tgcData[k].toInt()); + } + + return dataTemp; + } + + static QStringList getTgcListFromRow(QSqlTableModel* tableModel, int rowNumber, int dataNumber) + { + auto tgcData = + tableModel->record(rowNumber).value("DATA" + + QString::number(dataNumber)).toString().split(',', + QString::SkipEmptyParts); + + return tgcData; + } + + static QList > getTgcDataFromRow(int i, QSqlTableModel* tableModel) + { + QList > allData; + for(int j = 10; j <= TGC_COUNT; ++j) + { + auto tgcData = getTgcListFromRow(tableModel, i, j); + + QList dataTemp = pripareTgcList(tgcData); + + allData.append(dataTemp); + + dataTemp.clear(); + } + + return allData; + } + + static bool insertInitUserTgcFromFactory(int userId, + QSqlTableModel* tableModel) + { + DbmDtoUserTgc userTgc; + getUserTgcByUsername(FACTORY, tableModel, userTgc); + userTgc.User_Id = userId; + tableModel->clear(); + + return setUserTgcByUserId(userId, tableModel, userTgc); + } + + static QSqlRecord createUserTgcRecord(DbmDtoUserTgc& userTgc) + { + QSqlRecord newRec; + QSqlField uId("User_id", QVariant::Int); + uId.setValue(userTgc.User_Id); + QSqlField data19("data10", QVariant::String); + data19.setValue(StaticUtility::convertListToString(userTgc.userTgcData.at(0))); + QSqlField data20("data11", QVariant::String); + data20.setValue(StaticUtility::convertListToString(userTgc.userTgcData.at(1))); + QSqlField data21("data12", QVariant::String); + data21.setValue(StaticUtility::convertListToString(userTgc.userTgcData.at(2))); + + newRec.append(uId); + newRec.append(data19); + newRec.append(data20); + newRec.append(data21); + + return newRec; + } + + static bool selectFromUserTgc(QSqlTableModel* tableModel, QString filter = "") + { + tableModel->setTable("UserTgc"); + if(!filter.isEmpty()) + { + tableModel->setFilter(filter); + } + + bool ret = tableModel->select(); + + return ret; + } + +public: + static bool getUserTgcss(QSqlTableModel* tableModel, QList& userTgcs) + { + bool ret = selectFromUserTgc(tableModel); + DbmDtoUserTgc userIns; + + for(int i = 0; i < tableModel->rowCount(); ++i) + { + if(tableModel->record(i).value("ID").toInt() > 0) + { + DbmDtoUserTgc tgcTemp; + tgcTemp.userTgcData.append(getTgcDataFromRow(i, tableModel)); + + tgcTemp.ID = tableModel->record(i).value("ID").toInt(); + + tgcTemp.User_Id = tableModel->record(i).value("User_Id").toInt(); + + userTgcs.append(tgcTemp); + } + } + + return ret; + } + + static bool getUserTgcByUserId(int userId, + QSqlTableModel* tableModel, + DbmDtoUserTgc& userTgc) + { + auto filter = QString("User_Id is %1").arg(userId); + bool ret = selectFromUserTgc(tableModel, filter); + + if(tableModel->rowCount() < 1) + { + insertInitUserTgcFromFactory(userId, tableModel); + ret = tableModel->select(); + if(!ret) + { + return false; + } + } + + userTgc.userTgcData.append(getTgcDataFromRow(0, tableModel)); + + userTgc.ID = tableModel->record(0).value("ID").toInt(); + + userTgc.User_Id = tableModel->record(0).value("User_Id").toInt(); + + return ret; + } + + static bool getUserTgcByUsername(QString username, + QSqlTableModel* tableModel, + DbmDtoUserTgc& userTgc) + { + tableModel->setTable("UserTgc"); + int userId = getUserIDByUsername(username, tableModel); + if(userId > 0) + { + auto ret = getUserTgcByUserId(userId, tableModel, userTgc); + + return ret; + } + + return false; + } + + static bool setUserTgcByUserId(int userId, + QSqlTableModel* tableModel, + DbmDtoUserTgc& userTgc) + { + bool ret; + auto filter = QString("User_Id is %1").arg(userId); + auto noError = selectFromUserTgc(tableModel, filter); + if(!noError) + { + return false; + } + if(tableModel->rowCount() > 0) + { + ret = tableModel->setData(tableModel->index(0, 1), 2); + QVariant data10; + data10.setValue(StaticUtility::convertListToString(userTgc.userTgcData.at( + 0))); + ret = tableModel->setData(tableModel->index(0, 2), data10); + + QVariant data11; + data11.setValue(StaticUtility::convertListToString(userTgc.userTgcData.at( + 0))); + ret = tableModel->setData(tableModel->index(0, 3), data11); + + QVariant data12; + data12.setValue(StaticUtility::convertListToString(userTgc.userTgcData.at( + 0))); + ret = tableModel->setData(tableModel->index(0, 4), data12); + + ret = tableModel->submit(); + } + else + { + userTgc.User_Id = userId; + QSqlRecord newRec = createUserTgcRecord(userTgc); + ret = tableModel->insertRecord(-1, newRec); + } + + return ret; + } + + static bool setUserTgcByUsername(QString username, + QSqlTableModel* tableModel, + DbmDtoUserTgc& userTgc) + { + bool ret; + int userId = getUserIDByUsername(username, tableModel); + if(userId == 0) + { + return false; + } + + return setUserTgcByUserId(userId, tableModel, userTgc); + } + + static bool updateUserTgcFieldByUserId(QSqlTableModel* tableModel, + int userId, + int index, + QList tgc) + { + auto filter = QString("User_Id is %1").arg(userId); + auto noError = selectFromUserTgc(tableModel, filter); + if(!noError) + { + return false; + } + int trueIndex = index + 2; //0 : id | 1 : User_Id + QVariant data; + data.setValue(StaticUtility::convertListToString(tgc)); + bool ret = tableModel->setData(tableModel->index(0, trueIndex), data); + ret = tableModel->submit(); + + return ret; + } + + static bool updateUserTgcFieldByUsername(QSqlTableModel* tableModel, + QString username, + int index, + QList tgc) + { + int userId = getUserIDByUsername(username, tableModel); + if(userId > 0) + { + return updateUserTgcFieldByUserId(tableModel, userId, index, tgc); + } + + return false; + } +}; + +#endif //DBMUSERTGC_H diff --git a/include/model/databaseManager/type/EAlgorithmType.h b/include/model/databaseManager/type/EAlgorithmType.h new file mode 100644 index 0000000..56272b7 --- /dev/null +++ b/include/model/databaseManager/type/EAlgorithmType.h @@ -0,0 +1,155 @@ +#ifndef ALGORITHMTYPE_H +#define ALGORITHMTYPE_H + +#include + +/*****************************************************************************/ +/** + * @brief This is an Enum Class for setting String names from table`s attribure + * that they are meaningful to coresponding enums for readability + * @author Mohammad Mohsen Talaie + * @details + * @date 5 oct 2020 + */ +/*****************************************************************************/ +class EAlgorithmType : QObject +{ +private: + //Private constructor prevent the enumeration class from being instantiated + explicit EAlgorithmType(QObject* parent = nullptr); + +public: + enum eEnhanceAlgorithmType : quint8 + { + sharpen, + laplacianOfGaussian + }; + + Q_ENUM(eEnhanceAlgorithmType) + + enum eSriAlgorithmType : quint8 + { + LeeFilter + }; + + Q_ENUM(eSriAlgorithmType) + + enum epwFftWinNameType : quint8 + { + blackman + }; + + Q_ENUM(epwFftWinNameType) + + QString spwFftWinNameType[1]{"blackman"}; + + /*****************************************************************************/ + /** + * @brief convert Enhance Algorithm name into enum + * @details this function convert enhance Algorithm name int eEnhanceAlgorithmType + * @return return corespondinc eEnhanceAlgorithmType from string + */ + /*****************************************************************************/ + static eEnhanceAlgorithmType convertEnhanceAlgorithmToEnum(const QString& name) + { + return QVariant(name).value(); + } + + /*****************************************************************************/ + /** + * @brief Convert eEnhanceAlgorithmType id into string. + * @details This function return name of coresponding algorithm. + * @return return algorithm name as QString + */ + /*****************************************************************************/ + static QString qtEnumToQString(const eEnhanceAlgorithmType qtEnum) + { + return QString(QMetaEnum::fromType().valueToKey(qtEnum)); + } + + /*****************************************************************************/ + /** + * @brief Convert Convert enhahance eEnhanceAlgorithmType name into int. + * @details his function return id of coresponding algorithm name. + * @return return algorithm id as int + */ + /*****************************************************************************/ + static int qtEnumToInt(const eEnhanceAlgorithmType qtEnum) + { + return QMetaEnum::fromType().value(qtEnum); + } + + /*****************************************************************************/ + /** + * @brief convert Sri Algorithm name into enum + * @details this function convert Sri Algorithm name int eSriAlgorithmType + * @return return corespondinc eSriAlgorithmType from string + */ + /*****************************************************************************/ + static eSriAlgorithmType convertSriAlgorithmToEnum(const QString name) + { + return QVariant(name).value(); + } + + /*****************************************************************************/ + /** + * @brief Convert eSriAlgorithmType into string. + * @details This function return name of coresponding algorithm. + * @return return algorithm name as QString + */ + /*****************************************************************************/ + static QString qtEnumToQString(const eSriAlgorithmType qtEnum) + { + return QString(QMetaEnum::fromType().valueToKey(qtEnum)); + } + + /*****************************************************************************/ + /** + * @brief Convert Convert eSriAlgorithmType name into int. + * @details his function return id of coresponding algorithm name. + * @return return algorithm id as int + */ + /*****************************************************************************/ + static int qtEnumToInt(const eSriAlgorithmType qtEnum) + { + return QMetaEnum::fromType().value(qtEnum); + } + + /*****************************************************************************/ + /** + * @brief convert PwFft Win name into enum + * @details this function convert PwFft Win name int eSriAlgorithmType + * @return return corespondinc eSriAlgorithmType from string + */ + /*****************************************************************************/ + static epwFftWinNameType convertPwFftWinToEnum(const QString name) + { + return QVariant(name).value(); + } + + /*****************************************************************************/ + /** + * @brief Convert epwFftWinNameType into string. + * @details This function return name of coresponding algorithm. + * @return return algorithm name as QString + */ + /*****************************************************************************/ + static QString qtEnumToQString(const epwFftWinNameType qtEnum) + { + return QString(QMetaEnum::fromType().valueToKey(qtEnum)); + } + + /*****************************************************************************/ + /** + * @brief Convert Convert epwFftWinNameType name into int. + * @details his function return id of coresponding algorithm name. + * @return return algorithm id as int + */ + /*****************************************************************************/ + static int qtEnumToInt(const epwFftWinNameType qtEnum) + { + return QMetaEnum::fromType().value(qtEnum); + } +}; + +#endif //ALGORITHMTYPE_H diff --git a/include/model/databaseManager/type/EDatabaseRequest.h b/include/model/databaseManager/type/EDatabaseRequest.h new file mode 100644 index 0000000..208e877 --- /dev/null +++ b/include/model/databaseManager/type/EDatabaseRequest.h @@ -0,0 +1,61 @@ +#ifndef EDATABASEREQUEST_H +#define EDATABASEREQUEST_H + +#include + +/*****************************************************************************/ +/** + * @brief Database requests class + * @details this class contains request enum + * @author Mohammad Mohsen Talaie + * @date 20 sep 2020 + */ +/*****************************************************************************/ +class EDatabaseRequest : public QObject +{ + Q_OBJECT + +private: + //add private constructor to avoid enumeration class initation. + explicit EDatabaseRequest(QObject* parent = nullptr); + +public: + enum eDatabaseRequest : qint32 + { + getProbeParametersByGlobalId, + getApplicationsByProbeId, + getPresetsByApplicationId, + getPresetValues, + getSysParameters, + getGrayMap, + getTGC, + getAllTintMap, + getTintMapByName, + getSri, + getDynamicContrast, + getCriFilter, + getEnhance, + getLineFilter, + getLpf, + getApodizationLut, + getUsers, + getUserByUsername, + getUserGrayMaps, + getUserGrayMapByUserId, + getUserGrayMapByUsername, + getLastConfig, + + //write + setAllUserGrayMap, + setUserGrayMapByUsernameAndIndex, + setUserGrayMapByUserIdAndIndex, + setAllUserTgc, + setUserTgcByUsernameAndIndex, + setUserTgcByUserIdAndIndex, + setLastConfig + }; + + Q_ENUM(eDatabaseRequest) +}; + +#endif //EDATABASEREQUEST_H diff --git a/include/model/databaseManager/type/ETintMapName.h b/include/model/databaseManager/type/ETintMapName.h new file mode 100644 index 0000000..956ec22 --- /dev/null +++ b/include/model/databaseManager/type/ETintMapName.h @@ -0,0 +1,54 @@ +#ifndef ETINTMAPNAME_H +#define ETINTMAPNAME_H + +#include + +/*****************************************************************************/ +/** + * @brief This is an Enum Class for setting String names from table`s attribure + * that they are meaningful to coresponding enums for readability + * @author Mohammad Mohsen Talaie + * @details + * @date 5 oct 2020 + */ +/*****************************************************************************/ +class ETintMapName : QObject +{ +private: + //Private constructor prevent the enumeration class from being instantiated + explicit ETintMapName(QObject* parent = nullptr); + +public: + enum eTintMapName : quint8 + { + sharpen + }; + + Q_ENUM(eTintMapName) + + /*****************************************************************************/ + /** + * @brief Convert eTintMapName id into string. + * @details This function return name of coresponding tintmap. + * @return return tintmap name as QString + */ + /*****************************************************************************/ + static QString qtEnumToQString(const eTintMapName qtEnum) + { + return QString(QMetaEnum::fromType().valueToKey(qtEnum)); + } + + /*****************************************************************************/ + /** + * @brief Convert Convert enhahance eTintMapName name into int. + * @details his function return id of coresponding tintmap name. + * @return return tintmap id as int + */ + /*****************************************************************************/ + static int qtEnumToInt(const eTintMapName qtEnum) + { + return QMetaEnum::fromType().value(qtEnum); + } +}; + +#endif //ETINTMAPNAME_H diff --git a/include/model/databaseManager/utils/StaticUtility.h b/include/model/databaseManager/utils/StaticUtility.h new file mode 100644 index 0000000..75150c5 --- /dev/null +++ b/include/model/databaseManager/utils/StaticUtility.h @@ -0,0 +1,25 @@ +#ifndef STATICUTILITY_H +#define STATICUTILITY_H + +#include + +class StaticUtility +{ +public: + template + static QString convertListToString(QList input) + { + QString ret; + for(int i = 0; i < input.count(); ++i) + { + T temp = input.at(i); + ret = QString("%1,%2").arg(ret).arg(temp); + } + + return ret; + } +}; + +//template static QString StaticUtility::convertListToString(QList input); + +#endif //STATICUTILITY_H diff --git a/include/model/databaseManager/utils/XmlReader.h b/include/model/databaseManager/utils/XmlReader.h new file mode 100644 index 0000000..1781edb --- /dev/null +++ b/include/model/databaseManager/utils/XmlReader.h @@ -0,0 +1,39 @@ +#ifndef XMLREADER_H +#define XMLREADER_H + +#include +#include + +#include "logger/Logger.h" + +class XmlReader : public QObject +{ + Q_OBJECT + +private: + inline void handleError(ESeverityLevel::eSeverityLevel severityLevel, + ELogID::eLogID logID, + QString logText, + bool emitThrow = true) const; + + QDomDocument _xmlDoc; + QString _xmlAddress; + QDomElement _root; + QList _dbNameVector; + QList _dbElementVector; + +public: + XmlReader(QString xmlAddress); + + QList getDatabaseNameList(); + QList getDBTableList(QString DBName); + QList getDBTableList(QDomElement DBElement); + QString getCreateTableQuery(QString tableName, QString DBName); + QString getCreateTableQuery(QString tableName, QDomElement DBElement); + QString getCreateAllTableQuery(QString DBName); + QString getCreateAllTableQuery(QDomElement DBElement); + QString getCreateInitialInsertQuery(QString DBName); + QString getInsertQuery(QString tableName, QString DBName); +}; + +#endif //XMLREADER_H diff --git a/include/model/databaseManager/utils/initializationUtils.h b/include/model/databaseManager/utils/initializationUtils.h new file mode 100644 index 0000000..e5db3e9 --- /dev/null +++ b/include/model/databaseManager/utils/initializationUtils.h @@ -0,0 +1,156 @@ +#ifndef INITIALIZATIONUTILS_H +#define INITIALIZATIONUTILS_H + +#include +#include +#include + +#include "model/databaseManager/core/DatabaseManagerNames.h" + +#define INIT_SINGLE(objectName, tableModel, fieldName, type, q) \ + do \ + { \ + objectName.fieldName = tableModel->record(q).value(#fieldName).to ## type(); \ + } \ + while(0) + +#define INIT_SINGLE_STR(objectName, tableModel, fieldName, q) \ + do \ + { \ + objectName.fieldName = tableModel->record(q).value(#fieldName); \ + } \ + while(0) \ + +#define INIT_SINGLE_STR_TO_ENUM(objectName, tableModel, fieldName, convertorFunction, q) \ + do \ + { \ + objectName.fieldName = \ + convertorFunction(tableModel->record(q).value(#fieldName).toString()); \ + } \ + while(0) \ + +#define INIT_LIST(objectName, tableModel, fieldName, Type, q) \ + do \ + { \ + auto _ ## fieldName = tableModel->record(q).value(#fieldName).toString().split(',', \ + QString::SkipEmptyParts); \ + for(int i = 0; i < _ ## fieldName.length(); ++i) \ + { \ + objectName.fieldName.append(_ ## fieldName[i].to ## Type()); \ + } \ + } \ + while(0) + +#define INIT_LIST_STR(objectName, tableModel, fieldName, q) \ + do \ + { \ + auto _ ## fieldName = tableModel->record(q).value(#fieldName).toString().split(',', \ + QString::SkipEmptyParts); \ + for(int i = 0; i < _ ## fieldName.length(); ++i) \ + { \ + objectName.fieldName.append(_ ## fieldName[i]); \ + } \ + } \ + while(0) \ + +#define INTI_LIST_LIST(objectName, tableModel, fieldName, type, Type, q) \ + do { \ + auto _ ## fieldName = tableModel->record(q).value(#fieldName).toString().split(';', \ + QString::SkipEmptyParts); \ + for(int i = 0; i < _ ## fieldName.length(); ++i){ \ + auto __ ## fieldName = _ ## fieldName[i].split(',', QString::SkipEmptyParts); \ + QList temp; \ + for(int j = 0; j < __ ## fieldName.length(); ++j) \ + { \ + temp.append(__ ## fieldName[j].to ## Type()); \ + } \ + objectName.fieldName.append(temp); \ + temp.clear(); \ + } \ + } while(0) + +#define GET_DATA(dbName, databaseDriver, objectName, funcName, var) \ + do { \ + auto databaseName = createDbName(dbName); \ + databaseDriver.setDatabaseName(databaseName); \ + databaseDriver.open(); \ + QSqlTableModel* tableModel = new QSqlTableModel(this, databaseDriver); \ + tableModel->clear(); \ + Dbm ## objectName ins ## objectName; \ + DbmDto ## objectName objectName ## Data; \ + if(ins ## objectName.funcName(tableModel, objectName ## Data)) \ + { \ + var.setValue(objectName ## Data); \ + result = true; \ + } \ + else \ + { \ + result = false; \ + } \ + delete tableModel; \ + } while(0) + +#define GET_DATA_PARAM(dbName, databaseDriver, objectName, funcName, param, var) \ + do { \ + auto databaseName = createDbName(dbName); \ + databaseDriver.setDatabaseName(databaseName); \ + databaseDriver.open(); \ + QSqlTableModel* tableModel = new QSqlTableModel(this, databaseDriver); \ + tableModel->clear(); \ + Dbm ## objectName ins ## objectName; \ + DbmDto ## objectName objectName ## Data; \ + if(ins ## objectName.funcName(param, tableModel, objectName ## Data)) \ + { \ + var.setValue(objectName ## Data); \ + result = true; \ + } \ + else \ + { \ + result = false; \ + } \ + delete tableModel; \ + } while(0) + +#define GET_DATA_LIST_PARAM(dbName, databaseDriver, objectName, funcName, param, var) \ + do { \ + auto databaseName = createDbName(dbName); \ + databaseDriver.setDatabaseName(databaseName); \ + databaseDriver.open(); \ + QSqlTableModel* tableModel = new QSqlTableModel(this, databaseDriver); \ + tableModel->clear(); \ + Dbm ## objectName ins ## objectName; \ + QList objectName ## Data; \ + if(ins ## objectName.funcName(param, tableModel, objectName ## Data)) \ + { \ + var.setValue(objectName ## Data); \ + result = true; \ + } \ + else \ + { \ + result = false; \ + } \ + delete tableModel; \ + } while(0) + +#define GET_DATA_LIST(dbName, databaseDriver, objectName, funcName, var) \ + do { \ + auto databaseName = createDbName(dbName); \ + databaseDriver.setDatabaseName(databaseName); \ + databaseDriver.open(); \ + QSqlTableModel* tableModel = new QSqlTableModel(this, databaseDriver); \ + tableModel->clear(); \ + Dbm ## objectName ins ## objectName; \ + QList objectName ## Data; \ + if(ins ## objectName.funcName(tableModel, objectName ## Data)) \ + { \ + var.setValue(objectName ## Data); \ + result = true; \ + } \ + else \ + { \ + result = false; \ + } \ + delete tableModel; \ + } while(0) + +#endif //INITIALIZATIONUTILS_H diff --git a/include/model/enums/EDataType.h b/include/model/enums/EDataType.h new file mode 100644 index 0000000..dfadb19 --- /dev/null +++ b/include/model/enums/EDataType.h @@ -0,0 +1,30 @@ +#ifndef EDATATYPE_H +#define EDATATYPE_H + +#include + +class EDataType +{ +public: + enum eDataType : quint8 + { + bData, + mData, + cData, + cmData + }; + + /*************************************************************************************************/ + /** + * @brief int to enaum value converter + * @param int Enumerator to be converted to the relevant value + * @return int value relevant to the eDataType enumerator + */ + /*************************************************************************************************/ + static eDataType intToEnum(const quint8 intEnum) + { + return static_cast(intEnum); + } +}; + +#endif //EDATATYPE_H diff --git a/include/model/enums/EUsMode.h b/include/model/enums/EUsMode.h new file mode 100644 index 0000000..d84768c --- /dev/null +++ b/include/model/enums/EUsMode.h @@ -0,0 +1,12 @@ +#ifndef USMODE_H +#define USMODE_H +enum EUsMode +{ + bMode, + b_MMode, + bCMode, + bC_MMode, + bPDMode, + bPWMode +}; +#endif // USMODE_H diff --git a/include/model/evocator/Evocator.h b/include/model/evocator/Evocator.h new file mode 100644 index 0000000..4863cc1 --- /dev/null +++ b/include/model/evocator/Evocator.h @@ -0,0 +1,41 @@ +#ifndef EVOCATOR_H +#define EVOCATOR_H + +#include + +#include "model/ultrasoundModule/UsData.h" +#include "model/ultrasoundModule/UsModule.h" +#include "model/evocator/core/EvocatorCore.h" +#include "model/player/Player.h" +#include "model/backendImageProcessor/Bip.h" +#include "model/bipTester/BipTester.h" + +/*************************************************************************************************/ +/** + * @brief This is a UsModule that stor exam data and images. + * @author Mohammad Mohsen Talaie + * @details This module store exam data for restoring data and reproducing + * exam. + * This module only store, and replaying and reproducing is not due of this + * module. + * @date 21 sep 2020 + */ +/*************************************************************************************************/ +class Evocator : public UsModule +{ + Q_OBJECT + US_MODULE + SINGLETON(Evocator) + +private: + EvocatorCore* _core; + Evocator(); + +public: + ~Evocator() override; + +signals: + void sendBufferToPlayer(QList >); +}; + +#endif //EVOCATOR_H diff --git a/include/model/evocator/core/EvocatorCore.h b/include/model/evocator/core/EvocatorCore.h new file mode 100644 index 0000000..de53fb6 --- /dev/null +++ b/include/model/evocator/core/EvocatorCore.h @@ -0,0 +1,54 @@ +#ifndef EVOCATORCORE_H +#define EVOCATORCORE_H + +#include +#include +#include +#include + +#include "model/evocator/metadata/EvocatorMetadata.h" +#include "model/ultrasoundModule/UsPacket.h" +#include "model/ultrasoundModule/metadata/HardwareMetadata.h" +#include "model/evocator/dto/CineDisplayParameters.h" + +#define CACHE_SIZE 512 * 1024 * 1024 + +Q_DECLARE_METATYPE(QList >) + +/*****************************************************************************/ +/** + * @brief Core of Evocator + * @author Mohammad Mohsen Talaie + * @details This class do the core instruction of evocator. + * @date 20 sep 2020 + */ +/*****************************************************************************/ +class EvocatorCore : public QObject +{ + Q_OBJECT + +private: + QQueue _queue; + int _packetCount = 0; + int _occupatedMemory = 0; + QQueue _buffer[2]; + EvocatorMetadata _metadata; + +public: + EvocatorCore() + { + } + + ~EvocatorCore(); + QList > getBuffer(); + void calculateEvocatorCapacity(unsigned long sizeOfPacket); + bool appendTempQueueToBuffer(); + bool putIntoQueue(const UsPacket& inputPacket); + bool closeQueue(); + bool reset(); + EvocatorMetadata getMetaData(); + void getCineLiveData(CineDisplayParameters_t* dispParams); + void getCineFreezedData(CineDisplayParameters_t* dispParams); +}; + +#endif //EVOCATORCORE_H diff --git a/include/model/evocator/dto/CineDisplayParameters.h b/include/model/evocator/dto/CineDisplayParameters.h new file mode 100644 index 0000000..7c879bd --- /dev/null +++ b/include/model/evocator/dto/CineDisplayParameters.h @@ -0,0 +1,15 @@ +#ifndef CINEDISPLAYPARAMETERS_H +#define CINEDISPLAYPARAMETERS_H + +#include + +typedef struct CineDisplayParameters_t { + int maxSecondCapacity = 0; + int currentSecound = 0; + int currentIndex = 0; + int maxFrameCapacity = 0; +}CineDisplayParameters_t; + +Q_DECLARE_METATYPE(CineDisplayParameters_t) + +#endif //CINEDISPLAYPARAMETERS_H diff --git a/include/model/evocator/dto/EvocatorMetaDataPart.h b/include/model/evocator/dto/EvocatorMetaDataPart.h new file mode 100644 index 0000000..7ee5490 --- /dev/null +++ b/include/model/evocator/dto/EvocatorMetaDataPart.h @@ -0,0 +1,60 @@ +#ifndef EVOCATORMETADATAPART_H +#define EVOCATORMETADATAPART_H + +#include + +#include "model/evocator/dto/EvocatorProbeProperties.h" + +/*************************************************************************************************/ +/** + * @brief Evocator metadata part include scenario generator parameter + * @author Mohammad Mohsen Talaie + * @details This is a dto for copy senario generator parameters inside evocator meta data + * @date 21 sep 2020 + */ +/*************************************************************************************************/ +typedef struct EvocatorMetaDataPart_t +{ + EvocatorProbeProperties_t probe; + bool virtualConvex; + bool hdZoom; + float depth; + float fieldOfView; + float startDepth; + int rxLineNo; + int rxFocusPointNo; + float rxLineDaz; + float rxPointDax; + float vcMaxTheta; + float angle; + float steering; + float minScanAx; + float maxScanAx; + float minScanAz; + float bMinScanAx; + float bMinScanAz; + float bMaxScanAx; + float bMaxScanAz; + float virtualOriginalZ; + uint outputWidth; + uint outputHeight; + int compressionType; + int dynContSelector; + int dynContGain; + int grayMapSelector; + bool tintMapEnable; + int sri; + int rejectThreshold; + int enhance; + int enhanceAlgorithm; + int enhanceFilterSize; + int persist; + int frameFilterMode; + int cri; + int criFilterMode; + QList tintMap; + QList enhanceAlpha; + QList enhanceSigma; +}EvocatorMetaDataPart_t; + +#endif //EVOCATORMETADATAPART_H diff --git a/include/model/evocator/dto/EvocatorProbeProperties.h b/include/model/evocator/dto/EvocatorProbeProperties.h new file mode 100644 index 0000000..15562a2 --- /dev/null +++ b/include/model/evocator/dto/EvocatorProbeProperties.h @@ -0,0 +1,20 @@ +#ifndef EVOCATORPROBEPROPERTIES_H +#define EVOCATORPROBEPROPERTIES_H + +/*************************************************************************************************/ +/** + * @brief Prob Properties dto for evocator meta data. + * @author Mohammad Mohsen Talaie + * @details Evocator shuld has Prob Properties for save buffer. So Evocator save this in it`s meta + * data. + * @date 2020 + */ +/*************************************************************************************************/ +typedef struct EvocatorProbeProperties_t +{ + bool linear; + float radius; + float fieldOfView; +}EvocatorProbeProperties_t; + +#endif //EVOCATORPROBEPROPERTIES_H diff --git a/include/model/evocator/metadata/EvocatorMetadata.h b/include/model/evocator/metadata/EvocatorMetadata.h new file mode 100644 index 0000000..0bd4b2b --- /dev/null +++ b/include/model/evocator/metadata/EvocatorMetadata.h @@ -0,0 +1,40 @@ +#ifndef EVOCATORMETADATA_H +#define EVOCATORMETADATA_H + +#include +#include +#include + +#include "model/evocator/dto/EvocatorMetaDataPart.h" +#include "model/ultrasoundModule/metadata/UsBaseMetadata.h" + +/*************************************************************************************************/ +/** + * @brief Evocator metadata store system parameters that they determine + * configuration of system. + * @author Mohammad Mohsen Talaie + * @details This data is usefull for check the parameters whene exam have been + * taken.Changing system parameters that saved in meta data leads to reset + * Evocator and this meta data. + * @date 21 sep 2020 + */ +/*************************************************************************************************/ +class EvocatorMetadata : public UsBaseMetadata +{ +public: + EvocatorMetadata(); + int fps; + int bCountInMemory; + int secondInMemory; + float mSpeed; + float lineSpeedRecord; + bool lineCurserMode; + QDateTime timeTag; + QUuid id; + EvocatorMetaDataPart_t _senGenParams; + bool clear(); +}; + +Q_DECLARE_METATYPE(EvocatorMetadata) + +#endif //EVOCATORMETADATA_H diff --git a/include/model/hardware/Hardware.h b/include/model/hardware/Hardware.h new file mode 100644 index 0000000..2b7536a --- /dev/null +++ b/include/model/hardware/Hardware.h @@ -0,0 +1,35 @@ +#ifndef HARDWARE_H +#define HARDWARE_H + +#include +#include + +#include "model/ultrasoundModule/UsModule.h" +#include "model/hardware/core/HardwareCore.h" + +/** + * @brief The singleton Hardware class + * @details Is treated as the actual hardware in our model and is responsible for reflecting it. + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2019/8/5(1398/5/14) + */ + +class Hardware : public UsModule +{ + Q_OBJECT + US_MODULE + SINGLETON(Hardware) + +private: + HardwareCore* _hardwareCore; + + Hardware(); + ~Hardware() override; + +//uncrustify off +public slots: +//uncrudtify on + void newPacketReady(const UsPacket& packet); +}; + +#endif //HARDWARE_H diff --git a/include/model/hardware/core/Fan.h b/include/model/hardware/core/Fan.h new file mode 100644 index 0000000..ac66fd6 --- /dev/null +++ b/include/model/hardware/core/Fan.h @@ -0,0 +1,24 @@ +#ifndef FAN_H +#define FAN_H + +#include + +#include "model/hardware/core/Status.h" + +class Fan +{ +private: + QString _name; + uint32_t _rpm; + bool _lock; + +public: + Fan(QString name); + void Update(); + QString getName(); + uint32_t getRpm(); + bool isLock(); + +}; + +#endif // FAN_H diff --git a/include/model/hardware/core/HardwareCore.h b/include/model/hardware/core/HardwareCore.h new file mode 100644 index 0000000..a41ab25 --- /dev/null +++ b/include/model/hardware/core/HardwareCore.h @@ -0,0 +1,44 @@ +#ifndef HARDWARE_CORE_H +#define HARDWARE_CORE_H + +#include + +#include "model/hardware/core/IBoard.h" +#include "model/ultrasoundModule/UsData.h" +#include "model/hardware/core/TrxBoard.h" + +class HardwareCore : public QObject +{ + Q_OBJECT + +private: + TrxBoard* _trxBoard; + + bool selfTest(); + bool functionalTest() { + return true; + } + + void createTrxBoard(); + void initTrxBoard(); + + bool hwProcFileExist(); + void checkPcieLink(); + void programFpga(); + + QString getApplicationHomePath(); + +public: + HardwareCore(); + ~HardwareCore(); + + void start(); + void dataReady(const QByteArray& arr); + + void startupRoutine(); + +signals: + void newData(const QByteArray& arr); +}; + +#endif //HARDWARE_CORE_H diff --git a/include/model/hardware/core/HwBoard.h b/include/model/hardware/core/HwBoard.h new file mode 100644 index 0000000..41a55cb --- /dev/null +++ b/include/model/hardware/core/HwBoard.h @@ -0,0 +1,34 @@ +#ifndef TRXBOARD_H +#define TRXBOARD_H + +#include "model/hardware/device/SonoDevice.h" +#include "model/hardware/service/HardwarePacketEngine.h" + +class HwBoard +{ +private: + QString _name; + QString _version; + + SonoDevice _device; + int _swCounter; + int _hwCounter; + bool _run; + +public: + HardwarePacketEngine packetEngine; + + HwBoard(); + QString getName(); + QString getVersion(); + bool selfTest(); + bool updateInfo(); + bool updateStatus(); + void readData(); + void init(); + void start(); + void stop(); + void programSlave(); +}; + +#endif //TRXBOARD_H diff --git a/include/model/hardware/core/IBoard.h b/include/model/hardware/core/IBoard.h new file mode 100644 index 0000000..ff51faf --- /dev/null +++ b/include/model/hardware/core/IBoard.h @@ -0,0 +1,24 @@ +#ifndef IBOARD_H +#define IBOARD_H + +#include + +/** + * @brief IBoard interface defention + * @details This is the interface for all low level boards in hardware + * (i.e. Relay, TRX, Power) + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2019/8/5(1398/5/14) + */ +class IBoard +{ +public: + virtual ~IBoard(){} + virtual QString getName() = 0; + virtual QString getVersion() = 0; + virtual bool selfTest() = 0; + virtual bool updateInfo() = 0; + virtual bool updateStatus() = 0; +}; + +#endif // IBOARD_H diff --git a/include/model/hardware/core/IBoardFactory.h b/include/model/hardware/core/IBoardFactory.h new file mode 100644 index 0000000..a281f13 --- /dev/null +++ b/include/model/hardware/core/IBoardFactory.h @@ -0,0 +1,13 @@ +#ifndef BOARDFACTORY_H +#define BOARDFACTORY_H + +#include "model/hardware/core/IBoard.h" + +class IBoardFactory +{ +public: + virtual ~IBoardFactory () {} + virtual IBoard* create() = 0; +}; + +#endif // BOARDFACTORY_H diff --git a/include/model/hardware/core/PowerBoard.h b/include/model/hardware/core/PowerBoard.h new file mode 100644 index 0000000..bfecf8a --- /dev/null +++ b/include/model/hardware/core/PowerBoard.h @@ -0,0 +1,32 @@ +#ifndef POWERBOARD_H +#define POWERBOARD_H + +#include "model/hardware/core/IBoard.h" +#include "model/hardware/core/PowerBoardStatus.h" + +/** + * @brief Power board + * @details This class is reflecting the actual power board hardware + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2019/8/5(1398/5/14) + */ +class PowerBoard : public IBoard +{ +private: + QString _name; + QString _version; + quint32 _baseAddress; + +public: + PowerBoard(); + ~PowerBoard(); + virtual QString getName(); + virtual QString getVersion(); + virtual bool selfTest(); + virtual bool updateInfo(); + virtual bool updateStatus(); + + PowerBoardStatus* Status; +}; + +#endif // POWERBOARD_H diff --git a/include/model/hardware/core/PowerBoardFactory.h b/include/model/hardware/core/PowerBoardFactory.h new file mode 100644 index 0000000..15a0cea --- /dev/null +++ b/include/model/hardware/core/PowerBoardFactory.h @@ -0,0 +1,13 @@ +#ifndef POWERBOARDFACTORY_H +#define POWERBOARDFACTORY_H + +#include "model/hardware/core/IBoardFactory.h" + +class PowerBoardFactory : public IBoardFactory +{ +public: + PowerBoardFactory(){} + IBoard* create() override; +}; + +#endif // POWERBOARDFACTORY_H diff --git a/include/model/hardware/core/PowerBoardStatus.h b/include/model/hardware/core/PowerBoardStatus.h new file mode 100644 index 0000000..ec1ed67 --- /dev/null +++ b/include/model/hardware/core/PowerBoardStatus.h @@ -0,0 +1,18 @@ +#ifndef POWERBOARDSTATUS_H +#define POWERBOARDSTATUS_H + +#include "model/hardware/core/Temperature.h" +#include "model/hardware/core/Fan.h" +#include "model/hardware/core/Voltage.h" + +class PowerBoardStatus +{ +public: + PowerBoardStatus(); + ~PowerBoardStatus(); + Voltage* Voltages[1]; + Temperature* temperature; + Fan* fan; +}; + +#endif // POWERBOARDSTATUS_H diff --git a/include/model/hardware/core/RelayBoard.h b/include/model/hardware/core/RelayBoard.h new file mode 100644 index 0000000..f17ec56 --- /dev/null +++ b/include/model/hardware/core/RelayBoard.h @@ -0,0 +1,22 @@ +#ifndef RELAYBOARD_H +#define RELAYBOARD_H + +#include "model/hardware/core/IBoard.h" + +class RelayBoard : public IBoard +{ +private: + QString _name; + QString _version; + quint32 _baseAddress; + +public: + RelayBoard(); + virtual QString getName(); + virtual QString getVersion(); + virtual bool selfTest(); + virtual bool updateInfo(); + virtual bool updateStatus(); +}; + +#endif // RELAYBOARD_H diff --git a/include/model/hardware/core/RelayBoardFactory.h b/include/model/hardware/core/RelayBoardFactory.h new file mode 100644 index 0000000..ced8cb6 --- /dev/null +++ b/include/model/hardware/core/RelayBoardFactory.h @@ -0,0 +1,13 @@ +#ifndef RELAYBOARDFACTORY_H +#define RELAYBOARDFACTORY_H + +#include "model/hardware/core/IBoardFactory.h" + +class RelayBoardFactory : public IBoardFactory +{ +public: + RelayBoardFactory(){} + IBoard* create() override; +}; + +#endif // RELAYBOARDFACTORY_H diff --git a/include/model/hardware/core/Status.h b/include/model/hardware/core/Status.h new file mode 100644 index 0000000..436ffea --- /dev/null +++ b/include/model/hardware/core/Status.h @@ -0,0 +1,10 @@ +#ifndef STATUS_H +#define STATUS_H + +enum class Status +{ + GOOD, + BAD +}; + +#endif diff --git a/include/model/hardware/core/Temperature.h b/include/model/hardware/core/Temperature.h new file mode 100644 index 0000000..17a4f84 --- /dev/null +++ b/include/model/hardware/core/Temperature.h @@ -0,0 +1,23 @@ +#ifndef TEMPERATURE_H +#define TEMPERATURE_H + +#include + +#include "model/hardware/core/Status.h" + +class Temperature +{ +private: + QString _name; + float _value; + Status _status; + +public: + Temperature(QString name); + void Update(); + QString getName(); + float getValue(); + Status getStatus(); +}; + +#endif // TEMPERATURE_H diff --git a/include/model/hardware/core/TrxBoard.h b/include/model/hardware/core/TrxBoard.h index a145d21..41d3609 100644 --- a/include/model/hardware/core/TrxBoard.h +++ b/include/model/hardware/core/TrxBoard.h @@ -1,10 +1,12 @@ #ifndef TRXBOARD_H #define TRXBOARD_H +#include +#include +#include #include #include #include -#include #include "model/hardware/core/register/clockDistributer/ClockDistributer.h" #include "model/hardware/core/register/boardsCtrlMngt/BoardsCtrlMngt.h" @@ -17,391 +19,263 @@ #include "model/hardware/core/register/misc/Misc.h" #include "model/hardware/core/register/sram/Sram.h" #include "model/hardware/core/register/dsp/Dsp.h" +#include "model/hardware/core/register/afe/Afe.h" #include "model/hardware/device/SonoDevice.h" -#define SLAVE_ELEMENT_SEGMENT 64U -#define TOTAL_SCEN_LUT_SRAM 5U -#define SLAVE_FPGA_NUMBER 1U -#define CLOCK_DIVISION 0x55 +#include "model/scenarioGenerator/dto/hardware/HardwareOutput.h" +#include "model/scenarioGenerator/core/general/Calculation.h" +#include "model/hardware/service/HardwarePacketEngine.h" -#define EEPROM_ID_BYTE_BEGIN 19U -#define EEPROM_ID_BYTE_NUMBER 2U -#define EEPROM_INFO_BYTE_BEGIN 0U -#define EEPROM_INFO_BYTE_NUMBER 19U +#define SLAVE_ELEMENT_SEGMENT 64U +#define TOTAL_SCEN_LUT_SRAM 6U +#define SLAVE_FPGA_NUMBER 3U +#define CLOCK_DIVISION 0x55 + +#define EEPROM_ID_BYTE_BEGIN 19U +#define EEPROM_ID_BYTE_NUMBER 2U +#define EEPROM_INFO_BYTE_BEGIN 0U +#define EEPROM_INFO_BYTE_NUMBER 19U enum eEmulatorOption : bool { - performance = false, - functionality = true + performance = false, + functionality = true }; enum eEmulatorMode : bool { - dynamically = false, - statically = true + dynamically = false, + statically = true }; enum eAfePwrdnMode : bool { - disable = false, - enable = true + disable = false, + enable = true }; enum eSelectProbe : quint8 { - prbA = 1, - prbB, - prbC, - prbD, + prbA = 1, + prbB, + prbC, + prbD +}; + +enum eSlaveSelect : quint8 +{ + slave0, + slave1, + slave2 }; struct EmulatorProperties { - quint32 ramBufAddress; - quint32 transferLength; - float transferRate; - eEmulatorMode emulMode; - eEmulatorOption emulOption; + quint32 ramBufAddress; + quint32 transferLength; + float transferRate; + eEmulatorMode emulMode; + eEmulatorOption emulOption; }; struct ProbeElementPosition { - QVector xPosition; - QVector yPosition; - QVector zPosition; + QVector xPosition; + QVector yPosition; + QVector zPosition; }; struct HealthStatus { - float systemTemperature; - float criticalComponentTemperature; - AdcVoltages* adcMon; - VoltagesPg* voltsPg; + float systemTemperature; + float criticalComponentTemperature; + AdcVoltages* adcMon; + VoltagesPg* voltsPg; }; struct ConnectedPrbId { - quint32 prbA; - quint32 prbB; - quint32 prbC; - quint32 prbD; + quint32 prbA; + quint32 prbB; + quint32 prbC; + quint32 prbD; }; struct ConnectedPrbInfo { - QByteArray prbA; - QByteArray prbB; - QByteArray prbC; - QByteArray prbD; -}; - - -typedef struct Pulse_t { - quint32 halfPeriod; - quint32 halfCycleNo; - bool pulseVoltSel; - bool startPhase; - quint32 dampingPulseWidth; -}Pulse_t; - -struct RxBeamFormer_t { - quint32 mla; - quint32 lag; - quint32 apodizationSel; -}; - -struct ReceiverConfig_t { - quint32 mla; - quint32 lineMode; - quint32 aTgcSel; - quint32 stbEn; - quint32 stb; - quint32 subtractFilterEn; - quint32 dcCancelEn; - quint32 ncoFreqSel; - quint32 lpfSel; - quint32 absEn; - quint32 focusNo; - quint32 lineFilterEn; -}; - - -struct SramIndex_t { - QVector shotPropertiesIndex; - QVector pulsePropertiesIndex; - QVector receiverConfigurationIndex; - QVector firstLineInFrame; - QVector lastLineInFrame; - QVector dLineNum; - QVector dEnsembleNum; -}; - -struct SramTx_t { - QVector txFocusXPos; - QVector txFocusYPos; - QVector txFocusZPos; - QVector txStartActiveElementNumber; - QVector txActiveElementNumber; - QVector minDelay; - QVector maxDelay; - QVector maxDelayQ; - QVector interceptXPos; - QVector interceptYPos; - QVector interceptZPos; - - void clear() - { - txFocusXPos.clear(); - txFocusYPos.clear(); - txFocusZPos.clear(); - txStartActiveElementNumber.clear(); - txActiveElementNumber.clear(); - minDelay.clear(); - maxDelay.clear(); - maxDelayQ.clear(); - interceptXPos.clear(); - interceptYPos.clear(); - interceptZPos.clear(); - } + QByteArray prbA; + QByteArray prbB; + QByteArray prbC; + QByteArray prbD; }; -struct SramRx_t { - QVector rxR0CenterActiveElementNumber; - QVector rxR0ActiveElementNumber; - QVector rxActiveElementStep; - QVector interceptPointFiringTime; - QVector r0Position; - QVector rxFocusPointNumber; - QVector thetaCos; - QVector thetaSin; - QVector phiCos; - QVector phiSin; - QVector interceptXPos; - QVector interceptYPos; - QVector interceptZPos; - QVector txR0MinDelay; - QVector rxR0MinDelay; - QVector rxR0MaxDelay; - QVector txR0MinDelayQ; - QVector rxR0MinDelayQ; - QVector rxR0MaxDelayQ; - QVector rxR0StartActiveElementNumber; - QVector r0XPosition; - QVector r0YPosition; - QVector r0ZPosition; - - void clear() - { - rxR0CenterActiveElementNumber.clear(); - rxR0ActiveElementNumber.clear(); - rxActiveElementStep.clear(); - interceptPointFiringTime.clear(); - r0Position.clear(); - rxFocusPointNumber.clear(); - thetaCos.clear(); - thetaSin.clear(); - phiCos.clear(); - phiSin.clear(); - interceptXPos.clear(); - interceptYPos.clear(); - interceptZPos.clear(); - txR0MinDelay.clear(); - rxR0MinDelay.clear(); - rxR0MaxDelay.clear(); - txR0MinDelayQ.clear(); - rxR0MinDelayQ.clear(); - rxR0MaxDelayQ.clear(); - rxR0StartActiveElementNumber.clear(); - r0XPosition.clear(); - r0YPosition.clear(); - r0ZPosition.clear(); - } -}; - - -struct HwRegister_t { - QVector dtgcLut; - QVector > blendWeight; - QVector elementXPosition; - QVector elementYPosition; - QVector elementZPosition; - QVector freqLut; - quint32 scenarioStartIndex; - quint32 scenarioEndIndex; - QList pulseProps; - quint8 pulseTypeNumber; - quint8 rxBeamFormerTypeNumber; - QList rxBeamFormerProps; - quint8 receiverConfigTypeNumber; - QList receiverConfigProps; - QList> lpfLut; - QList> atgcLut; - QList > apodizationLut; -}; - -struct ScenGenHardwareOutput_t -{ - quint32 focusTypeNumber; - quint32 totalTxShotNumber; - QVector rxBeamFormerNumber; - QVector pulseInterval; - - HwRegister_t hwRegister; - SramIndex_t indexParams; - SramRx_t rxParams; - SramTx_t txParams; -}; - - class TrxBoard { private: - QVector _swapVec; - QVector _unsignedQntzrVec; - QList* _mcsList; - const quint32 _offsetSlave0; - const quint32 _offsetSlave1; - const quint32 _offsetSlave2; - bool _allow; + QVector _swapVec; + QVector _floatQntzrVec; + QList _unsignedQntzrList; + QList* _mcsList; + QList _afeModuleOffset; + QList _fpgaOffset; + const quint32 _offsetSlave0; + const quint32 _offsetSlave1; + const quint32 _offsetSlave2; - int _swCounter; - int _hwCounter; + bool _allow; bool _run; + int _swCounter; + int _hwCounter; + + SonoDevice _device; + AdcVoltages* _adc; + VoltagesPg* _pg; + + ClockDistributer* _clkDistributer; + BeamFormer* _beamFormerSlave0; + BeamFormer* _beamFormerSlave1; + BeamFormer* _beamFormerSlave2; + BoardsCtrlMngt* _bCtrlMngt; + FpgaProgram* _fpgaProgram; + ScenPalyer* _scenPlayer; + BpiFlash* _bpiFlash; + Afe* _afeSlave0; + Afe* _afeSlave1; + Afe* _afeSlave2; + Emulator* _emul; + Misc* _misc; + Sram* _sram; + Dsp* _dsp; + + enum eScenParams : quint8 + { + clear, + set + }; + + struct HwRegister + { + ///////////// BeamFormer ///////////// + RxBeamformerProperties* rxBeamformer; + QList > apodization; + ProbeElementPosition* elementPosition; + PulseProperties* pulse; + quint8 pulseTypeNumber; + quint8 rxBeamFormerTypeNumber; + + //////////////// DSP //////////////// + QVector freqLut; + QVector dtgcLut; + QList > lpfLut; + QList > atgcLut; + ReceiverConfiguration* configLut; + QVector > blendWeight; + quint8 receiverConfigTypeNumber; + HwRegister(); + ~HwRegister(); + }; + + struct ScenGenHardwareOutput { + quint32 focusTypeNumber; + quint32 totalTxShotNumber; + QVector rxBeamFormerNumber; + quint32 scenarioStartIndex; + quint32 scenarioEndIndex; + + HwRegister* hwRegister; + SramIndex* indexParams; + SramRx* rxParams; + SramTx* txParams; + ScenGenHardwareOutput(); + ~ScenGenHardwareOutput(); + } + * scenParams; + + HardwarePacketEngine packetEngine; + + void setScenario(ScenGenHardwareOutput* scenParams); + + void setSwapVector(void); + void setFpgaOffset (void); + void setAfeModuleOffset (void); + void scenParamsFilling(eScenParams cmd); + QList floatVector2unsignedList (QVector& fVec); - SonoDevice _device; - AdcVoltages* _adc; - VoltagesPg* _pg; - - ClockDistributer* _clkDistributer; - BoardsCtrlMngt* _bCtrlMngt; - FpgaProgram* _fpgaProgram; - BeamFormer* _beamFormerSlave0; - BeamFormer* _beamFormerSlave1; - BeamFormer* _beamFormerSlave2; - ScenPalyer* _scenPlayer; - BpiFlash* _bpiFlash; - Emulator* _emul; - Misc* _misc; - Sram* _sram; - Dsp* _dsp; - - enum eScenParams : quint8 - { - clear, - set - }; - - struct HwRegister - { - ///////////// BeamFormer ///////////// - RxBeamformerProperties* rxBeamformer; - QList> apodization; - ProbeElementPosition* elementPosition; - PulseProperties* pulse; - //AfeProperties* afe; - quint8 pulseTypeNumber; - quint8 rxBeamFormerTypeNumber; - - //////////////// DSP //////////////// - QVector freqLut; - QVector dtgcLut; - QList> lpfLut; - QList> atgcLut; - ReceiverConfiguration* configLut; - QVector> blendWeight; - quint8 receiverConfigTypeNumber; - HwRegister(); - ~HwRegister(); - }; - - struct ScenGenHardwareOutput { - quint32 focusTypeNumber; - quint32 totalTxShotNumber; - QVector rxBeamFormerNumber; - quint32 scenarioStartIndex; - quint32 scenarioEndIndex; - - HwRegister* hwRegister; - SramIndex* indexParams; - SramRx* rxParams; - SramTx* txParams; - ScenGenHardwareOutput(); - ~ScenGenHardwareOutput(); - }*scenParams; - - void setScenario (ScenGenHardwareOutput* scenParams); - void scenParamsFilling(eScenParams cmd); - void setSwapVector (void); - //QList signedVector2unsignedList (QVector& sgnVec); +signals: + void sendFramePacket (const QByteArray newPacket) const; + public: - TrxBoard(); - ~TrxBoard(); + TrxBoard(); + ~TrxBoard(); - ////////////////////////////////// Scenario API /////////////////////////////// - void setLineFilterCoefficient (QVector& lineFilterLut); - void setStbCoefficient (QVector& stbLut); - void setDtgcLut (QVector& dtgcLut); + ///////////////////////////////// Initialize API ////////////////////////////// + void init(void); + ////////////////////////////////// Scenario API /////////////////////////////// + void setLineFilterCoefficient(QVector& lineFilterLut); + void setStbCoefficient(QVector& stbLut); + void setDtgcLut(QVector& dtgcLut); - void setAtgcMode (eAtgcMode mode, quint16 value) const; + void setAtgcMode(eAtgcMode mode, quint16 value) const; - void setScenario (ScenGenHardwareOutput_t scenGenHw); + void setMetaData(const QByteArray metaData) const; - void setAfePwrdnMode (eAfePwrdnMode cmd) const; - void setAfeConfig (AfeProperties* afe) const; + void setScenario(ScenGenHardwareOutput_t scenGenHw); - void scenPlayerStart (void) const; - //void scenPlayerPause (bool pause) const; - void scenPlayerStop (void) const; + void setAfeConfig(AfeConfig afe); + void setAfePwrdnMode(eAfePwrdnMode cmd) const; + QList getAfeReg(eSlaveSelect sel, quint32 afeRegAddr); - ////////////////////////////// Slave Programming API /////////////////////////// - void slaveFpgaProgram (QString path); + void scenPlayerStart(void); + void scenPlayerStop(void); + //void scenPlayerPause (bool pause) const; - /////////////////////////////// BeamFormer Mode API //////////////////////////// - void setBeamFormerMode (eClkMode mode) const; + ////////////////////////////// Slave Programming API /////////////////////////// + void slaveFpgaProgram(QString path); - ///////////////////////////////// Emulator API ///////////////////////////////// - void emulatorInit(EmulatorProperties* config) const; - void emulatorEnable(void) const; - void emulatorDisable(void) const; + /////////////////////////////// BeamFormer Mode API //////////////////////////// + void setBeamFormerMode(eClkMode mode) const; - ////////////////////////////// BoardCtrlMngt API /////////////////////////////// - quint32 deviceId (void) const; - quint32 vendorId (void) const; + ///////////////////////////////// Emulator API ///////////////////////////////// + void emulatorInit(EmulatorProperties* config) const; + void emulatorStart(QString path); + void emulatorStop(void); - quint32 trxId (void) const; - quint32 mpsId (void) const; - quint32 prbCtrlId (void) const; - quint32 prbId (quint8 prbSel) const; - void getConnectedPrbId (ConnectedPrbId* prbId) const; + ////////////////////////////// BoardCtrlMngt API /////////////////////////////// + quint32 deviceId(void) const; + quint32 vendorId(void) const; - QString trxInfo (void) const; - QString mpsInfo (void) const; - QString prbCtrlInfo (void) const; - QByteArray prbInfo (quint8 prbSel) const; - void getConnectedPrbInfo (ConnectedPrbInfo* prbInfo) const; + quint32 trxId(void) const; + quint32 mpsId(void) const; + quint32 prbCtrlId(void) const; + quint32 prbId(quint8 prbSel) const; + void getConnectedPrbId(ConnectedPrbId* prbId) const; - void supervisorRbValue(SupervisorRbValue* sValue) const; - void mpsFaultStatus (MpsFaultStatus* faultStatus) const; - void mpsReset (void) const; - void mpsSetAo (float voltA, float voltB) const; + QString trxInfo(void) const; + QString mpsInfo(void) const; + QString prbCtrlInfo(void) const; + QByteArray prbInfo(quint8 prbSel) const; + void getConnectedPrbInfo(ConnectedPrbInfo* prbInfo) const; - void selectProbe (eSelectProbe prbSel) const; - void getHealthStatus (HealthStatus* healStat) const; - void init (void) const; + void supervisorRbValue(SupervisorRbValue* sValue) const; + void mpsFaultStatus(MpsFaultStatus* faultStatus) const; + void mpsReset(void) const; + void mpsSetAo(float voltA, float voltB) const; - //////////////////////////////// BPI Flash API ///////////////////////////////// - void mcsProgram (QString path); - void mcsVerify (QString path) const; + void selectProbe(eSelectProbe prbSel) const; + void getHealthStatus(HealthStatus* healStat) const; - //////////////////////////////// Miscellaneous API ///////////////////////////////// - void getTrxStatus (StatusVec* status) const; - void getFpgasCodeVersion (FpgaCodeVersion* version) const; + //////////////////////////////// BPI Flash API ///////////////////////////////// + void mcsProgram(QString path); + void mcsVerify(QString path) const; - ///////////////////////////////// Old TRX ////////////////////////////////////// - void readData(); + //////////////////////////////// Miscellaneous API ///////////////////////////////// + void getTrxStatus(StatusVec* status) const; + void getFpgasCodeVersion(FpgaCodeVersion* version) const; + /////////////////////////////// DMA Data Packet //////////////////////////////////// + void readData(); }; -#endif // TRXBOARD_H +#endif //TRXBOARD_H diff --git a/include/model/hardware/core/TrxBoardFactory.h b/include/model/hardware/core/TrxBoardFactory.h new file mode 100644 index 0000000..69a2241 --- /dev/null +++ b/include/model/hardware/core/TrxBoardFactory.h @@ -0,0 +1,13 @@ +#ifndef TRXBOARDFACTORY_H +#define TRXBOARDFACTORY_H + +#include "model/hardware/core/IBoardFactory.h" + +class TrxBoardFactory : public IBoardFactory +{ +public: + TrxBoardFactory(){} + IBoard* create() override; +}; + +#endif // TRXBOARDFACTORY_H diff --git a/include/model/hardware/core/Voltage.h b/include/model/hardware/core/Voltage.h new file mode 100644 index 0000000..8460792 --- /dev/null +++ b/include/model/hardware/core/Voltage.h @@ -0,0 +1,25 @@ +#ifndef VOLTAGE_H +#define VOLTAGE_H + +#include + +#include "model/hardware/core/Status.h" + +class Voltage +{ +private: + QString _name; + float _value; + float _current; + Status _status; + +public: + Voltage(QString name); + void Update(); + QString getName(); + float getValue(); + float getCurrent(); + Status getStatus(); +}; + +#endif // VOLTAGE_H diff --git a/include/model/hardware/core/register/Field.h b/include/model/hardware/core/register/Field.h index c5d4a7a..2b4cbe5 100644 --- a/include/model/hardware/core/register/Field.h +++ b/include/model/hardware/core/register/Field.h @@ -7,48 +7,48 @@ class Field { private: quint32 _value; - quint64 _valueLong; + quint64 _valueLong; quint32 _mask; - quint64 _maskLong; + quint64 _maskLong; quint8 _length; quint8 _position; quint32 _zeroBasedMask; - quint64 _zeroBasedMaskLong; + quint64 _zeroBasedMaskLong; bool _isSigned; bool _isUpdated; Field(quint32 mask, bool isSigned); - Field(quint64 mask); + Field(quint64 mask); void findLength(); - void findLengthLong(); + void findLengthLong(); void findPosition(); - void findPositionLong(); + void findPositionLong(); void findZeroBasedMask(); - void findZeroBasedMaskLong(); + void findZeroBasedMaskLong(); public: static Field* fromBitPosition(quint32 bitPosition); static Field* fromMaskSigned(quint32 mask); static Field* fromMaskUnsigned(quint32 mask); - static Field* fromMaskUnsignedLong(quint64 maskLong); + static Field* fromMaskUnsignedLong(quint64 maskLong); quint32 getValue(); void setValue(quint32 value); - void setValueLong(quint64 valueLong); + void setValueLong(quint64 valueLong); bool isUpdated(); void updateValue(quint32 value); quint32 getRegisterWriteValue(); - quint64 getRegisterWriteValueLong(); + quint64 getRegisterWriteValueLong(); }; #endif //FIELD_H diff --git a/include/model/hardware/core/register/RegUtils.h b/include/model/hardware/core/register/RegUtils.h index bf233ac..429be3f 100644 --- a/include/model/hardware/core/register/RegUtils.h +++ b/include/model/hardware/core/register/RegUtils.h @@ -21,10 +21,4 @@ _fields.append(NAME); \ } while(0) -#define ADD_BIT_FIELD(NAME, MASK) \ - do { \ - NAME = Field::fromBitPosition(MASK); \ - _fields.append(NAME); \ - } while(0) - #endif //REGUTILS_H diff --git a/include/model/hardware/core/register/Register.h b/include/model/hardware/core/register/Register.h index cbb965f..2a7ce66 100644 --- a/include/model/hardware/core/register/Register.h +++ b/include/model/hardware/core/register/Register.h @@ -3,61 +3,54 @@ #include "model/hardware/core/register/Field.h" #include "model/hardware/device/SonoDevice.h" -#include -#include class Register { private: - virtual void prepareData(quint32){} - virtual void receiveData(void){} + virtual void prepareData(quint32) + { + } + + virtual void receiveData(void) + { + } protected: - quint32 _bar; - quint32 _offset; - quint32 _baseOffset; + quint32 _bar; + quint32 _offset; + quint32 _baseOffset; - quint32 _arrayLength; + quint32 _arrayLength; - quint32 _value; + quint32 _value; - bool _isUpdated; + bool _isUpdated; - QList _fields; + QList _fields; - SonoDevice* _device; + SonoDevice* _device; public: - Register(quint8 bar, quint32 offset, SonoDevice* device, quint32 arrayLength=0); // Constructor for general Registers: single and array - virtual ~Register(); - - quint32 getValue(); - void setValue(quint32 value); + //Constructor for general Registers: single and array + Register(quint8 bar, quint32 offset, SonoDevice* device, quint32 arrayLength = 0); + virtual ~Register(); - void changeOffset(quint32 offset); - quint32 getCurrentOffset (void) const; + quint32 getValue(); + void setValue(quint32 value); - bool isUpdated(); + void changeOffset(quint32 offset); + quint32 getCurrentOffset(void) const; - void update(); - void updateLong(); + bool isUpdated(); - void updateArray(bool isVariable=false, quint8 arrayLength=0); - void updateArrayLong(quint8 interval, quint32 arrayLength); + void update(); + void updateLong(); - void sync(); - void syncArray(); - - static QVector qntzr(QVector &data, - quint32 sign, - quint32 wordlength, - quint32 fractionalLength, - float maxLevel, - bool integerOutput, - bool useRound = true, - bool twosCmpl = false); + void updateArray(bool isVariable = false, quint8 arrayLength = 0); + void updateArrayLong(quint8 interval, quint32 arrayLength); + void sync(); + void syncArray(); }; - -#endif //rEGISTER_H +#endif //REGISTER_H diff --git a/include/model/hardware/core/register/afe/Afe.h b/include/model/hardware/core/register/afe/Afe.h new file mode 100644 index 0000000..5297db2 --- /dev/null +++ b/include/model/hardware/core/register/afe/Afe.h @@ -0,0 +1,52 @@ +#ifndef AFE_H +#define AFE_H + +#include "registerDefinition/ActiveTerm.h" +#include "registerDefinition/LnaHpf.h" +#include "registerDefinition/Global.h" +#include "registerDefinition/LowNf.h" +#include "registerDefinition/Pga.h" + +struct AfeConfig +{ + quint32 lpfProg; + bool pgaHpfDis; + bool pgaClampDis; + bool pgaClampLvl; + bool pgaGain; + quint32 activeTermIndRes; + bool activeTermIndResEn; + quint32 gblActiveTerm; + bool actTermEn; + quint32 inputClampLvl; + bool lnaHpfDis; + quint32 lnaGainGbl; + bool lowNf; + quint32 powModes; + quint32 lnaHpfProg; +}; + +class Afe +{ +private: + ActiveTerm* _actTerm; + LnaHpf* _lnaHpf; + Global* _global; + LowNf* _lowNf; + Pga* _pga; + + void setActTerm (const AfeConfig afe) const; + void setLnaHpf (const AfeConfig afe) const; + void setLowNf (const AfeConfig afe) const; + void setPga (const AfeConfig afe) const; + +public: + explicit Afe(SonoDevice* device, quint32 offset); + ~Afe(); + + void setAfeParams(const AfeConfig afe) const; + void setAfeGblPwr(const bool pwrdn) const; + void setReadRegEnable(const bool rdEn) const; +}; + +#endif // AFE_H diff --git a/include/model/hardware/core/register/afe/registerDefinition/ActiveTerm.h b/include/model/hardware/core/register/afe/registerDefinition/ActiveTerm.h new file mode 100644 index 0000000..ef7eed4 --- /dev/null +++ b/include/model/hardware/core/register/afe/registerDefinition/ActiveTerm.h @@ -0,0 +1,55 @@ +#ifndef ACTIVETERM_H +#define ACTIVETERM_H + +#include "model/hardware/core/register/Register.h" +#include "model/hardware/core/register/RegUtils.h" + +#undef BAR + +#define ACTIVE_TERM_IND_RES_MASK 0x0000001F +#define ACTIVE_TERM_IND_RES_EN_MASK 0x00000020 +#define GBL_ACTIVE_TERM_MASK 0x000000C0 +#define ACT_TERM_EN_MASK 0x00000100 +#define LNA_INPUT_CLAMP_LVL_MASK 0x00000600 +#define LNA_HPF_DIS_MASK 0x00001000 +#define LNA_GAIN_GBL_MASK 0x00006000 + +#define BAR 0U +#define OFFSET 0x43C310 + +class ActiveTerm : public Register +{ + +public: + Field* activeTermIndRes; + Field* activeTermIndResEn; + Field* gblActiveTerm; + Field* actTermEn; + Field* lnaInputClampLvl; + Field* lnaHpfDis; + Field* lnaGainGbl; + + ActiveTerm(SonoDevice* device, quint32 offset) : Register(BAR, OFFSET + offset, device) + { + ADD_UNSIGNED_FIELD(activeTermIndRes, ACTIVE_TERM_IND_RES_MASK); + ADD_UNSIGNED_FIELD(activeTermIndResEn, ACTIVE_TERM_IND_RES_EN_MASK); + ADD_UNSIGNED_FIELD(gblActiveTerm, GBL_ACTIVE_TERM_MASK); + ADD_UNSIGNED_FIELD(actTermEn, ACT_TERM_EN_MASK); + ADD_UNSIGNED_FIELD(lnaInputClampLvl, LNA_INPUT_CLAMP_LVL_MASK); + ADD_UNSIGNED_FIELD(lnaHpfDis, LNA_HPF_DIS_MASK); + ADD_UNSIGNED_FIELD(lnaGainGbl, LNA_GAIN_GBL_MASK); + } +}; + +#undef ACTIVE_TERM_IND_RES_MASK +#undef ACTIVE_TERM_IND_RES_EN_MASK +#undef GBL_ACTIVE_TERM_MASK +#undef ACT_TERM_EN_MASK +#undef LNA_INPUT_CLAMP_LVL_MASK +#undef LNA_HPF_DIS_MASK +#undef LNA_GAIN_GBL_MASK + +#undef BAR +#undef OFFSET + +#endif // ACTIVETERM_H diff --git a/include/model/hardware/core/register/afe/registerDefinition/Global.h b/include/model/hardware/core/register/afe/registerDefinition/Global.h new file mode 100644 index 0000000..0aad6a5 --- /dev/null +++ b/include/model/hardware/core/register/afe/registerDefinition/Global.h @@ -0,0 +1,31 @@ +#ifndef GLOBAL_H +#define GLOBAL_H + +#include "model/hardware/core/register/Register.h" +#include "model/hardware/core/register/RegUtils.h" + +#undef BAR + +#define REG_READ_EN_MASK 0x00000002 + +#define BAR 0U +#define OFFSET 0x43C000 + +class Global : public Register +{ + +public: + Field* regReadEn; + + Global(SonoDevice* device, quint32 offset) : Register(BAR, OFFSET + offset, device) + { + ADD_UNSIGNED_FIELD(regReadEn, REG_READ_EN_MASK); + } +}; + +#undef REG_READ_EN_MASK + +#undef BAR +#undef OFFSET + +#endif // GLOBAL_H diff --git a/include/model/hardware/core/register/afe/registerDefinition/LnaHpf.h b/include/model/hardware/core/register/afe/registerDefinition/LnaHpf.h new file mode 100644 index 0000000..81c2376 --- /dev/null +++ b/include/model/hardware/core/register/afe/registerDefinition/LnaHpf.h @@ -0,0 +1,31 @@ +#ifndef LNAHPF_H +#define LNAHPF_H + +#include "model/hardware/core/register/Register.h" +#include "model/hardware/core/register/RegUtils.h" + +#undef BAR + +#define LNA_HPF_PROG_MASK 0x0000000C + +#define BAR 0U +#define OFFSET 0x43C32C + +class LnaHpf : public Register +{ + +public: + Field* lnaHpfProg; + + LnaHpf(SonoDevice* device, quint32 offset) : Register(BAR, OFFSET + offset, device) + { + ADD_UNSIGNED_FIELD(lnaHpfProg, LNA_HPF_PROG_MASK); + } +}; + +#undef LNA_HPF_PROG_MASK + +#undef BAR +#undef OFFSET + +#endif // LNAHPF_H diff --git a/include/model/hardware/core/register/afe/registerDefinition/LowNf.h b/include/model/hardware/core/register/afe/registerDefinition/LowNf.h new file mode 100644 index 0000000..039fb6b --- /dev/null +++ b/include/model/hardware/core/register/afe/registerDefinition/LowNf.h @@ -0,0 +1,39 @@ +#ifndef LOWNF_H +#define LOWNF_H + +#include "model/hardware/core/register/Register.h" +#include "model/hardware/core/register/RegUtils.h" + +#undef BAR + +#define LOW_NF_MASK 0x00000200 +#define POW_MODES_MASK 0x00000C00 +#define GBL_PDWN_MASK 0x00008000 + +#define BAR 0U +#define OFFSET 0x43C314 + +class LowNf : public Register +{ + +public: + Field* lowNf; + Field* powModes; + Field* gblPdwn; + + LowNf(SonoDevice* device, quint32 offset) : Register(BAR, OFFSET + offset, device) + { + ADD_UNSIGNED_FIELD(lowNf, LOW_NF_MASK); + ADD_UNSIGNED_FIELD(powModes, POW_MODES_MASK); + ADD_UNSIGNED_FIELD(gblPdwn, GBL_PDWN_MASK); + } +}; + +#undef LOW_NF +#undef POW_MODES +#undef GBL_PDWN + +#undef BAR +#undef OFFSET + +#endif // LOWNF_H diff --git a/include/model/hardware/core/register/afe/registerDefinition/Pga.h b/include/model/hardware/core/register/afe/registerDefinition/Pga.h new file mode 100644 index 0000000..6d35a30 --- /dev/null +++ b/include/model/hardware/core/register/afe/registerDefinition/Pga.h @@ -0,0 +1,47 @@ +#ifndef PGA_H +#define PGA_H + +#include "model/hardware/core/register/Register.h" +#include "model/hardware/core/register/RegUtils.h" + +#undef BAR + +#define LPF_PROG_MASK 0x0000000F +#define PGA_HPF_DIS_MASK 0x00000010 +#define PGA_CLAMP_LVL_MASK 0x00000040 +#define PGA_CLAMP_DIS_MASK 0x00000080 +#define PGA_GAIN_MASK 0x00002000 + +#define BAR 0U +#define OFFSET 0x43C30C + +class Pga : public Register +{ + +public: + Field* lpfProg; + Field* pgaHpfDis; + Field* pgaClampLvl; + Field* pgaClampDis; + Field* pgaGain; + + Pga(SonoDevice* device, quint32 offset) : Register(BAR, OFFSET + offset, device) + { + ADD_UNSIGNED_FIELD(lpfProg, LPF_PROG_MASK); + ADD_UNSIGNED_FIELD(pgaHpfDis, PGA_HPF_DIS_MASK); + ADD_UNSIGNED_FIELD(pgaClampLvl, PGA_CLAMP_LVL_MASK); + ADD_UNSIGNED_FIELD(pgaClampDis, PGA_CLAMP_DIS_MASK); + ADD_UNSIGNED_FIELD(pgaGain, PGA_GAIN_MASK); + } +}; + +#undef LPF_PROG_MASK +#undef PGA_HPF_DIS_MASK +#undef PGA_CLAMP_LVL_MASK +#undef PGA_CLAMP_DIS_MASK +#undef PGA_GAIN_MASK + +#undef BAR +#undef OFFSET + +#endif // PGA_H diff --git a/include/model/hardware/core/register/beamFormer/registerDefinition/AfeLut.h b/include/model/hardware/core/register/beamFormer/registerDefinition/AfeLut.h index bffcdc0..8eb0221 100644 --- a/include/model/hardware/core/register/beamFormer/registerDefinition/AfeLut.h +++ b/include/model/hardware/core/register/beamFormer/registerDefinition/AfeLut.h @@ -6,120 +6,120 @@ #undef BAR -#define LPF_PROG_PRP_MASK 0x0000000F -#define PGA_HPF_DIS_PRP_MASK 0x00000010 -#define PGA_CLAMP_DIS_PRP_MASK 0x00000020 -#define PGA_GAIN_PRP_MASK 0x00000040 -#define GBL_ACTIVE_TERM_PRP_MASK 0x00000180 -#define ACT_TERM_EN_PRP_MASK 0x00000200 -#define INPUT_CLAMP_LVL_PRP_MASK 0x00000C00 -#define LNA_HPF_DIS_PRP_MASK 0x00001000 -#define LNA_GAIN_GBL_PRP_MASK 0x00006000 -#define LOW_NF_PRP_MASK 0x00008000 -#define POW_MODES_PRP_MASK 0x00030000 -#define GBL_PDWN_PRP_MASK 0x00040000 -#define LNA_HPF_PROG_PRP_MASK 0x00180000 - -#define BAR 0U -#define OFFSET 0x480800 -#define LENGTH 8U +#define LPF_PROG_PRP_MASK 0x0000000F +#define PGA_HPF_DIS_PRP_MASK 0x00000010 +#define PGA_CLAMP_DIS_PRP_MASK 0x00000020 +#define PGA_GAIN_PRP_MASK 0x00000040 +#define GBL_ACTIVE_TERM_PRP_MASK 0x00000180 +#define ACT_TERM_EN_PRP_MASK 0x00000200 +#define INPUT_CLAMP_LVL_PRP_MASK 0x00000C00 +#define LNA_HPF_DIS_PRP_MASK 0x00001000 +#define LNA_GAIN_GBL_PRP_MASK 0x00006000 +#define LOW_NF_PRP_MASK 0x00008000 +#define POW_MODES_PRP_MASK 0x00030000 +#define GBL_PDWN_PRP_MASK 0x00040000 +#define LNA_HPF_PROG_PRP_MASK 0x00180000 + +#define BAR 0U +#define OFFSET 0x480800 +#define LENGTH 8U struct AfeProperties { - QList lpfProg; - QList pgaHpfDis; - QList pgaClampDis; - QList pgaGain; - QList gblActiveTerm; - QList actTermEn; - QList inputClampLvl; - QList lnaHpfDis; - QList lnaGainGbl; - QList lowNf; - QList powModes; - QList gblPdwn; - QList lnaHpfProg; + QList lpfProg; + QList pgaHpfDis; + QList pgaClampDis; + QList pgaGain; + QList gblActiveTerm; + QList actTermEn; + QList inputClampLvl; + QList lnaHpfDis; + QList lnaGainGbl; + QList lowNf; + QList powModes; + QList gblPdwn; + QList lnaHpfProg; }; class AfeLut : public Register { private: - AfeProperties* _AfeLut; + AfeProperties* _AfeLut; - void prepareData(quint32 index) override - { - quint32 value=0; + void prepareData(quint32 index) override + { + quint32 value = 0; - lpfProgPrp->setValue(_AfeLut->lpfProg.at(static_cast(index))); + lpfProgPrp->setValue(_AfeLut->lpfProg.at(static_cast(index))); - value = _AfeLut->pgaHpfDis.at(static_cast(index)) ? 1 : 0; - pgaHpfDisPrp->setValue(value); + value = _AfeLut->pgaHpfDis.at(static_cast(index)) ? 1 : 0; + pgaHpfDisPrp->setValue(value); - value = _AfeLut->pgaClampDis.at(static_cast(index)) ? 1 : 0; - pgaClampDisPrp->setValue(value); + value = _AfeLut->pgaClampDis.at(static_cast(index)) ? 1 : 0; + pgaClampDisPrp->setValue(value); - value = _AfeLut->pgaGain.at(static_cast(index)) ? 1 : 0; - pgaGainPrp->setValue(value); + value = _AfeLut->pgaGain.at(static_cast(index)) ? 1 : 0; + pgaGainPrp->setValue(value); - gblActiveTermPrp->setValue(_AfeLut->gblActiveTerm.at(static_cast(index))); + gblActiveTermPrp->setValue(_AfeLut->gblActiveTerm.at(static_cast(index))); - value = _AfeLut->actTermEn.at(static_cast(index)) ? 1 : 0; - actTermEnPrp->setValue(value); + value = _AfeLut->actTermEn.at(static_cast(index)) ? 1 : 0; + actTermEnPrp->setValue(value); - inputClampLvlPrp->setValue(_AfeLut->inputClampLvl.at(static_cast(index))); + inputClampLvlPrp->setValue(_AfeLut->inputClampLvl.at(static_cast(index))); - value = _AfeLut->lnaHpfDis.at(static_cast(index)) ? 1 : 0; - lnaHpfDisPrp->setValue(value); + value = _AfeLut->lnaHpfDis.at(static_cast(index)) ? 1 : 0; + lnaHpfDisPrp->setValue(value); - lnaGainGblPrp->setValue(_AfeLut->lnaGainGbl.at(static_cast(index))); + lnaGainGblPrp->setValue(_AfeLut->lnaGainGbl.at(static_cast(index))); - value = _AfeLut->lowNf.at(static_cast(index)) ? 1 : 0; - lowNfPrp->setValue(value); + value = _AfeLut->lowNf.at(static_cast(index)) ? 1 : 0; + lowNfPrp->setValue(value); - powModesPrp->setValue(_AfeLut->powModes.at(static_cast(index))); + powModesPrp->setValue(_AfeLut->powModes.at(static_cast(index))); - value = _AfeLut->gblPdwn.at(static_cast(index)) ? 1 : 0; - gblPdwnPrp->setValue(value); + value = _AfeLut->gblPdwn.at(static_cast(index)) ? 1 : 0; + gblPdwnPrp->setValue(value); - lnaHpfProgPrp->setValue(_AfeLut->lnaHpfProg.at(static_cast(index))); - } + lnaHpfProgPrp->setValue(_AfeLut->lnaHpfProg.at(static_cast(index))); + } public: - Field* lpfProgPrp; - Field* pgaHpfDisPrp; - Field* pgaClampDisPrp; - Field* pgaGainPrp; - Field* gblActiveTermPrp; - Field* actTermEnPrp; - Field* inputClampLvlPrp; - Field* lnaHpfDisPrp; - Field* lnaGainGblPrp; - Field* lowNfPrp; - Field* powModesPrp; - Field* gblPdwnPrp; - Field* lnaHpfProgPrp; - - void setAfeLut (AfeProperties* AfeLut) - { - _AfeLut = AfeLut; - } - - AfeLut(SonoDevice* device, quint32 offset) : Register(BAR, OFFSET+offset, device, LENGTH) - { - ADD_UNSIGNED_FIELD(lpfProgPrp, LPF_PROG_PRP_MASK); - ADD_UNSIGNED_FIELD(pgaHpfDisPrp, PGA_HPF_DIS_PRP_MASK); - ADD_BIT_FIELD(pgaClampDisPrp, PGA_CLAMP_DIS_PRP_MASK); - ADD_BIT_FIELD(pgaGainPrp, PGA_GAIN_PRP_MASK); - ADD_UNSIGNED_FIELD(gblActiveTermPrp, GBL_ACTIVE_TERM_PRP_MASK); - ADD_UNSIGNED_FIELD(actTermEnPrp, ACT_TERM_EN_PRP_MASK); - ADD_UNSIGNED_FIELD(inputClampLvlPrp, INPUT_CLAMP_LVL_PRP_MASK); - ADD_UNSIGNED_FIELD(lnaHpfDisPrp, LNA_HPF_DIS_PRP_MASK); - ADD_UNSIGNED_FIELD(lnaGainGblPrp, LNA_GAIN_GBL_PRP_MASK); - ADD_UNSIGNED_FIELD(lowNfPrp, LOW_NF_PRP_MASK); - ADD_UNSIGNED_FIELD(powModesPrp, POW_MODES_PRP_MASK); - ADD_UNSIGNED_FIELD(gblPdwnPrp, GBL_PDWN_PRP_MASK); - ADD_UNSIGNED_FIELD(lnaHpfProgPrp, LNA_HPF_PROG_PRP_MASK); - } + Field* lpfProgPrp; + Field* pgaHpfDisPrp; + Field* pgaClampDisPrp; + Field* pgaGainPrp; + Field* gblActiveTermPrp; + Field* actTermEnPrp; + Field* inputClampLvlPrp; + Field* lnaHpfDisPrp; + Field* lnaGainGblPrp; + Field* lowNfPrp; + Field* powModesPrp; + Field* gblPdwnPrp; + Field* lnaHpfProgPrp; + + void setAfeLut (AfeProperties* AfeLut) + { + _AfeLut = AfeLut; + } + + AfeLut(SonoDevice* device, quint32 offset) : Register(BAR, OFFSET + offset, device, LENGTH) + { + ADD_UNSIGNED_FIELD(lpfProgPrp, LPF_PROG_PRP_MASK); + ADD_UNSIGNED_FIELD(pgaHpfDisPrp, PGA_HPF_DIS_PRP_MASK); + ADD_UNSIGNED_FIELD(pgaClampDisPrp, PGA_CLAMP_DIS_PRP_MASK); + ADD_UNSIGNED_FIELD(pgaGainPrp, PGA_GAIN_PRP_MASK); + ADD_UNSIGNED_FIELD(gblActiveTermPrp, GBL_ACTIVE_TERM_PRP_MASK); + ADD_UNSIGNED_FIELD(actTermEnPrp, ACT_TERM_EN_PRP_MASK); + ADD_UNSIGNED_FIELD(inputClampLvlPrp, INPUT_CLAMP_LVL_PRP_MASK); + ADD_UNSIGNED_FIELD(lnaHpfDisPrp, LNA_HPF_DIS_PRP_MASK); + ADD_UNSIGNED_FIELD(lnaGainGblPrp, LNA_GAIN_GBL_PRP_MASK); + ADD_UNSIGNED_FIELD(lowNfPrp, LOW_NF_PRP_MASK); + ADD_UNSIGNED_FIELD(powModesPrp, POW_MODES_PRP_MASK); + ADD_UNSIGNED_FIELD(gblPdwnPrp, GBL_PDWN_PRP_MASK); + ADD_UNSIGNED_FIELD(lnaHpfProgPrp, LNA_HPF_PROG_PRP_MASK); + } }; #undef LPF_PROG_PRP_MASK @@ -140,4 +140,4 @@ public: #undef OFFSET #undef LENGTH -#endif // AFELUT_H +#endif //AFELUT_H diff --git a/include/model/hardware/core/register/beamFormer/registerDefinition/ApodizationLut.h b/include/model/hardware/core/register/beamFormer/registerDefinition/ApodizationLut.h index 4295cd6..1925bef 100644 --- a/include/model/hardware/core/register/beamFormer/registerDefinition/ApodizationLut.h +++ b/include/model/hardware/core/register/beamFormer/registerDefinition/ApodizationLut.h @@ -6,35 +6,38 @@ #undef BAR -#define APODIZATION_PRP_MASK 0x0003FFFF +#define APODIZATION_PRP_MASK 0x0003FFFF -#define BAR 0 -#define OFFSET 0x4C0000 -#define LENGTH 3057U +#define BAR 0 +#define OFFSET 0x4C0000 +#define LENGTH 3057U class ApodizationLut : public Register { private: - QList _apodization; + QList _apodization; - void prepareData(quint32 index) override - { - apodizationPrp->setValue(_apodization.at(static_cast(index))); - //apodizationPrp->setValue(_apodization[static_cast(index)]); - } + void prepareData(quint32 index) override + { + apodizationPrp->setValue(_apodization.at(static_cast(index))); + //apodizationPrp->setValue(_apodization[static_cast(index)]); + } public: - Field* apodizationPrp; - - void setApodizationLut (QList& apodization) - { - _apodization = apodization; - } - - ApodizationLut(SonoDevice* device, quint32 offset) : Register(BAR, OFFSET+offset, device, LENGTH) - { - ADD_UNSIGNED_FIELD(apodizationPrp, APODIZATION_PRP_MASK); - } + Field* apodizationPrp; + + void setApodizationLut (QList& apodization) + { + _apodization = apodization; + } + + ApodizationLut(SonoDevice* device, quint32 offset) : Register(BAR, + OFFSET + offset, + device, + LENGTH) + { + ADD_UNSIGNED_FIELD(apodizationPrp, APODIZATION_PRP_MASK); + } }; #undef APODIZATION_PRP_MASK @@ -43,4 +46,4 @@ public: #undef OFFSET #undef LENGTH -#endif // APODIZATIONLUT_H +#endif //APODIZATIONLUT_H diff --git a/include/model/hardware/core/register/beamFormer/registerDefinition/ElementPositionLut.h b/include/model/hardware/core/register/beamFormer/registerDefinition/ElementPositionLut.h index 950bb78..0092a74 100644 --- a/include/model/hardware/core/register/beamFormer/registerDefinition/ElementPositionLut.h +++ b/include/model/hardware/core/register/beamFormer/registerDefinition/ElementPositionLut.h @@ -6,34 +6,37 @@ #undef BAR -#define ELEMENT_POSITION_PRP_MASK 0x0003FFFF +#define ELEMENT_POSITION_PRP_MASK 0x0003FFFF -#define BAR 0 -#define OFFSET 0X484000 -#define LENGTH 64U +#define BAR 0 +#define OFFSET 0X484000 +#define LENGTH 64U class ElementPositionLut : public Register { private: - QList _elementPosition; + QList _elementPosition; - void prepareData(quint32 index) override - { - elementPositionPrp->setValue(_elementPosition.at(static_cast(index))); - } + void prepareData(quint32 index) override + { + elementPositionPrp->setValue(_elementPosition.at(static_cast(index))); + } public: - Field* elementPositionPrp; - - void setElementPositionLut (QList& elementPosition) - { - _elementPosition = elementPosition; - } - - ElementPositionLut(SonoDevice* device, quint32 offset) : Register(BAR, OFFSET+offset, device, LENGTH) - { - ADD_UNSIGNED_FIELD(elementPositionPrp, ELEMENT_POSITION_PRP_MASK); - } + Field* elementPositionPrp; + + void setElementPositionLut (QList& elementPosition) + { + _elementPosition = elementPosition; + } + + ElementPositionLut(SonoDevice* device, quint32 offset) : Register(BAR, + OFFSET + offset, + device, + LENGTH) + { + ADD_UNSIGNED_FIELD(elementPositionPrp, ELEMENT_POSITION_PRP_MASK); + } }; #undef ELEMENT_POSITION_PRP_MASK @@ -42,4 +45,4 @@ public: #undef OFFSET #undef LENGTH -#endif // ELEMENTPOSITIONLUT_H +#endif //ELEMENTPOSITIONLUT_H diff --git a/include/model/hardware/core/register/beamFormer/registerDefinition/PulseLut.h b/include/model/hardware/core/register/beamFormer/registerDefinition/PulseLut.h index 881bde9..56284a4 100644 --- a/include/model/hardware/core/register/beamFormer/registerDefinition/PulseLut.h +++ b/include/model/hardware/core/register/beamFormer/registerDefinition/PulseLut.h @@ -72,8 +72,8 @@ public: { ADD_UNSIGNED_FIELD(halfPeriodPrp, HALF_PERIOD_PRP_MASK); ADD_UNSIGNED_FIELD(halfCycleNoPrp, HALF_CYCLE_NO_PRP_MASK); - ADD_BIT_FIELD(startPhasePrp, START_PHASE_PRP_MASK); - ADD_BIT_FIELD(pulseVoltSelPrp, PULSE_VOLT_SEL_PRP_MASK); + ADD_UNSIGNED_FIELD(startPhasePrp, START_PHASE_PRP_MASK); + ADD_UNSIGNED_FIELD(pulseVoltSelPrp, PULSE_VOLT_SEL_PRP_MASK); ADD_UNSIGNED_FIELD(dampingPulseWidthPrp, DAMPING_PULSE_WIDTH_PRP_MASK); } }; diff --git a/include/model/hardware/core/register/boardsCtrlMngt/registerDefinition/trx/TrxRegulatorPg.h b/include/model/hardware/core/register/boardsCtrlMngt/registerDefinition/trx/TrxRegulatorPg.h index 8e2dc23..8eccb15 100644 --- a/include/model/hardware/core/register/boardsCtrlMngt/registerDefinition/trx/TrxRegulatorPg.h +++ b/include/model/hardware/core/register/boardsCtrlMngt/registerDefinition/trx/TrxRegulatorPg.h @@ -20,8 +20,8 @@ public: TrxRegulatorPg(SonoDevice* device) : Register(BAR, OFFSET, device) { - ADD_BIT_FIELD(regA, REG_A_MASK); - ADD_BIT_FIELD(regB, REG_B_MASK); + ADD_UNSIGNED_FIELD(regA, REG_A_MASK); + ADD_UNSIGNED_FIELD(regB, REG_B_MASK); } }; diff --git a/include/model/hardware/core/register/bpiFlash/BpiFlash.h b/include/model/hardware/core/register/bpiFlash/BpiFlash.h index 359eb3d..8cab905 100644 --- a/include/model/hardware/core/register/bpiFlash/BpiFlash.h +++ b/include/model/hardware/core/register/bpiFlash/BpiFlash.h @@ -2,6 +2,7 @@ #define BPIFLASH_H #include "registerDefinition/McsRdWr.h" +#include "model/hardware/core/register/fpgaProgram/FpgaProgram.h" class BpiFlash { @@ -14,8 +15,6 @@ public: void writeMcs (QByteArray& mcs) const; void readMcs (QList* mcs) const; - - }; #endif // BPIFLASH_H diff --git a/include/model/hardware/core/register/dsp/registerDefinition/ReceiverConfigurationLut.h b/include/model/hardware/core/register/dsp/registerDefinition/ReceiverConfigurationLut.h index ab6f1aa..f050aa6 100644 --- a/include/model/hardware/core/register/dsp/registerDefinition/ReceiverConfigurationLut.h +++ b/include/model/hardware/core/register/dsp/registerDefinition/ReceiverConfigurationLut.h @@ -31,18 +31,18 @@ struct ReceiverConfiguration QList mla; QList lineMode; QList aTgcSel; - QList stbEn; + QList stbEn; QList stb; - QList subtractFilterEn; - QList dcCancelerEn; + QList subtractFilterEn; + QList dcCancelerEn; QList ncoFreqSel; QList lpfSel; - QList absEn; + QList absEn; QList focusNo; - QList lineFilterEn; - QList ddcEn; - QList wmfEn; - QList dpeEn; + QList lineFilterEn; + QList ddcEn; + QList wmfEn; + QList dpeEn; void clear() { mla.clear(); @@ -70,7 +70,7 @@ private: void prepareData(quint32 index) override { - quint32 value=0; + //quint32 value=0; mlaPrp->setValue(_configLut->mla.at(static_cast(index)) - 1); @@ -78,37 +78,37 @@ private: atgcSelPrp->setValue(_configLut->aTgcSel.at(static_cast(index)) - 1); - value = _configLut->stbEn.at(static_cast(index)) ? 1 : 0; - stbEnPrp->setValue(value); + //value = _configLut->stbEn.at(static_cast(index)) ? 1 : 0; + stbEnPrp->setValue(_configLut->stbEn.at(static_cast(index))); stbPrp->setValue(_configLut->stb.at(static_cast(index))); - value = _configLut->subtractFilterEn.at(static_cast(index)) ? 1 : 0; - subtractFilterEnPrp->setValue(value); + //value = _configLut->subtractFilterEn.at(static_cast(index)) ? 1 : 0; + subtractFilterEnPrp->setValue(_configLut->subtractFilterEn.at(static_cast(index))); - value = _configLut->dcCancelerEn.at(static_cast(index)) ? 1 : 0; - dcCancelEnPrp->setValue(value); + //value = _configLut->dcCancelerEn.at(static_cast(index)) ? 1 : 0; + dcCancelEnPrp->setValue(_configLut->dcCancelerEn.at(static_cast(index))); ncoFreqSelPrp->setValue(_configLut->ncoFreqSel.at(static_cast(index)) - 1); lpfSelPrp->setValue(_configLut->lpfSel.at(static_cast(index)) - 1); - value = _configLut->absEn.at(static_cast(index)) ? 1 : 0; - absEnPrp->setValue(value); + //value = _configLut->absEn.at(static_cast(index)) ? 1 : 0; + absEnPrp->setValue(_configLut->absEn.at(static_cast(index))); focusNoPrp->setValue(_configLut->focusNo.at(static_cast(index)) - 1); - value = _configLut->lineFilterEn.at(static_cast(index)) ? 1 : 0; - lineFilterEnPrp->setValue(value); + //value = _configLut->lineFilterEn.at(static_cast(index)) ? 1 : 0; + lineFilterEnPrp->setValue(_configLut->lineFilterEn.at(static_cast(index))); - value = _configLut->ddcEn.at(static_cast(index)) ? 1 : 0; - ddcEnPrp->setValue(value); + //value = _configLut->ddcEn.at(static_cast(index)) ? 1 : 0; + ddcEnPrp->setValue(_configLut->ddcEn.at(static_cast(index))); - value = _configLut->wmfEn.at(static_cast(index)) ? 1 : 0; - wmfEnPrp->setValue(value); + //value = _configLut->wmfEn.at(static_cast(index)) ? 1 : 0; + wmfEnPrp->setValue(_configLut->wmfEn.at(static_cast(index))); - value = _configLut->dpeEn.at(static_cast(index)) ? 1 : 0; - dpeEnPrp->setValue(value); + //value = _configLut->dpeEn.at(static_cast(index)) ? 1 : 0; + dpeEnPrp->setValue(_configLut->dpeEn.at(static_cast(index))); } public: diff --git a/include/model/hardware/core/register/fpgaProgram/FpgaProgram.h b/include/model/hardware/core/register/fpgaProgram/FpgaProgram.h index 9a8d5ef..9fb840b 100644 --- a/include/model/hardware/core/register/fpgaProgram/FpgaProgram.h +++ b/include/model/hardware/core/register/fpgaProgram/FpgaProgram.h @@ -4,7 +4,6 @@ #include #include #include -#include #include "registerDefinition/SlaveFpgaNumber.h" #include "registerDefinition/SerialProgramData.h" @@ -14,42 +13,43 @@ //#define FPGA_S1_DONE 2 //#define FPGA_S2_DONE 4 -#define FPGA_S0_INIT_B 1 -#define FPGA_S1_INIT_B 2 -#define FPGA_S2_INIT_B 4 +#define FPGA_S0_INIT_B 1 +#define FPGA_S1_INIT_B 2 +#define FPGA_S2_INIT_B 4 + +template +T byteArray2UintBigEndian(QByteArray& byte); class FpgaProgram { -private: - SerialProgramData* _progData; - SlaveFpgaNumber* _fpgaNumber; - - struct ProgramStatus { - SerialProgramStatus* _progStatus; - bool getProgramBusy() const; - bool getProgramDone() const; - bool getProgramFail() const; - bool getInitFail() const; - bool getProgramTimeout() const; - bool getFpgaS0InitB() const; - bool getFpgaS1InitB() const; - bool getFpgaS2InitB() const; -// bool getFpgaS0Done(); -// bool getFpgaS1Done(); -// bool getFpgaS2Done(); - }*_status; - - void setSlaveFpgaNumber (quint8& number) const; - +private: + SerialProgramData* _progData; + SlaveFpgaNumber* _fpgaNumber; + + struct ProgramStatus { + SerialProgramStatus* _progStatus; + bool getProgramBusy() const; + bool getProgramDone() const; + bool getProgramFail() const; + bool getInitFail() const; + bool getProgramTimeout() const; + bool getFpgaS0InitB() const; + bool getFpgaS1InitB() const; + bool getFpgaS2InitB() const; +//bool getFpgaS0Done(); +//bool getFpgaS1Done(); +//bool getFpgaS2Done(); + } + + * _status; + + void setSlaveFpgaNumber(quint8& number) const; public: - explicit FpgaProgram(SonoDevice* device); - ~FpgaProgram(); - - void program(QByteArray& bitFileData, quint8 number); + explicit FpgaProgram(SonoDevice* device); + ~FpgaProgram(); + void program(QByteArray& bitFileData, quint8 number); }; -quint32 byteArray2Uint32BigEndian(QByteArray& data); - -#endif // PROGRAM_H +#endif //PROGRAM_H diff --git a/include/model/hardware/core/register/sram/Sram.h b/include/model/hardware/core/register/sram/Sram.h index 9f2a355..101ed33 100644 --- a/include/model/hardware/core/register/sram/Sram.h +++ b/include/model/hardware/core/register/sram/Sram.h @@ -8,21 +8,26 @@ #include "registerDefinition/RxParamsDelay.h" #include "registerDefinition/TxParamsFocus.h" #include "registerDefinition/RxParamsDegree.h" +#include "registerDefinition/SoftwareMetaData.h" #define INDEX_INTERVAL 1U #define TX_RX_INTERVAL 27U #define INNER_RX_INTERVAL 3U +#define META_DATA_INTERVAL 1U +#define META_DATA_LENGTH 16U +#define META_DATA_OFFSET 0x400000 class Sram { private: - Index* _index; - TxParams* _tx; - TxParamsFocus* _txFocus; - RxParams* _rx; - RxParamsDegree* _rxDegree; - RxParamsPos* _rxPos; - RxParamsDelay* _rxDelay; + Index* _index; + TxParams* _tx; + TxParamsFocus* _txFocus; + RxParams* _rx; + RxParamsDegree* _rxDegree; + RxParamsPos* _rxPos; + RxParamsDelay* _rxDelay; + SoftwareMetaData* _metaData; public: explicit Sram(SonoDevice* device); @@ -31,7 +36,7 @@ public: void setSramIndex (quint32& totalTxShotNumber, SramIndex* index) const; void setSramTx (quint32& focusTypeNumber, SramTx* tx) const; void setSramRx (QVector& rxBeamFormerNumber, quint32& focusTypeNumber, SramRx* rx) const; - + void setSramMetaData(QList& metaData) const; }; #endif // SRAM_H diff --git a/include/model/hardware/core/register/sram/registerDefinition/RxParams.h b/include/model/hardware/core/register/sram/registerDefinition/RxParams.h index 6721792..38384f5 100644 --- a/include/model/hardware/core/register/sram/registerDefinition/RxParams.h +++ b/include/model/hardware/core/register/sram/registerDefinition/RxParams.h @@ -1,60 +1,62 @@ #ifndef RXPARAMS_H #define RXPARAMS_H +#include "model/scenarioGenerator/core/general/Calculation.h" #include "model/hardware/core/register/Register.h" #include "model/hardware/core/register/RegUtils.h" #include "SramStructures.h" #undef BAR -#define RX_ACTIVE_ELEMENT_STEP_MASK 0x00000000000000FF -#define INTERCEPT_POINT_FIRING_TIME_MASK 0x00000000000FFF00 -#define RX_FOCUS_POINT_NUMBER_MASK 0x00000001FFF00000 -#define R0_POSITION_MASK 0x0003FFFE00000000 - -#define BAR 1U -#define OFFSET 0x100010 -#define LENGTH 11264U +#define RX_ACTIVE_ELEMENT_STEP_MASK 0x00000000000000FF +#define INTERCEPT_POINT_FIRING_TIME_MASK 0x00000000000FFF00 +#define RX_FOCUS_POINT_NUMBER_MASK 0x00000001FFF00000 +#define R0_POSITION_MASK 0x0003FFFE00000000 +#define BAR 1U +#define OFFSET 0x100010 +#define LENGTH 11264U class RxParams : public Register { private: - SramRx* _rx; - QVector rxActiveElementStepQ; - QVector r0PositionQ; + SramRx* _rx; + QVector rxActiveElementStepQ; + QVector r0PositionQ; - void prepareData(quint32 index) override - { - rxActiveElementStep->setValueLong(rxActiveElementStepQ[static_cast(index)]); + void prepareData(quint32 index) override + { + rxActiveElementStep->setValueLong(static_cast(rxActiveElementStepQ[static_cast(index)])); - interceptPointFiringTime->setValueLong(_rx->interceptPointFiringTime[static_cast(index)]); + interceptPointFiringTime->setValueLong(_rx->interceptPointFiringTime[static_cast( + index)]); - rxFocusPointNumber->setValueLong(_rx->rxFocusPointNumber[static_cast(index)]) ; + rxFocusPointNumber->setValueLong(_rx->rxFocusPointNumber[static_cast(index)]); - r0Position->setValueLong(r0PositionQ[static_cast(index)]); - } + r0Position->setValueLong(static_cast (r0PositionQ[static_cast(index)])); + } public: - Field* rxActiveElementStep; - Field* interceptPointFiringTime; - Field* rxFocusPointNumber; - Field* r0Position; - - void setRxParams (SramRx* rx) - { - _rx = rx; - rxActiveElementStepQ = Register::qntzr(_rx->rxActiveElementStep, 0, 8, 8, 0, true, false); - r0PositionQ = Register::qntzr(_rx->r0Position, 0, 17, 0, 0, true); - } - - RxParams(SonoDevice* device) : Register(BAR, OFFSET, device, LENGTH) - { - ADD_UNSIGNED_FIELD_LONG(rxActiveElementStep, RX_ACTIVE_ELEMENT_STEP_MASK ); - ADD_UNSIGNED_FIELD_LONG(interceptPointFiringTime, INTERCEPT_POINT_FIRING_TIME_MASK); - ADD_UNSIGNED_FIELD_LONG(rxFocusPointNumber, RX_FOCUS_POINT_NUMBER_MASK ); - ADD_UNSIGNED_FIELD_LONG(r0Position, R0_POSITION_MASK ); - } + Field* rxActiveElementStep; + Field* interceptPointFiringTime; + Field* rxFocusPointNumber; + Field* r0Position; + + void setRxParams (SramRx* rx) + { + _rx = rx; + rxActiveElementStepQ = + Calculation::qntzr(_rx->rxActiveElementStep, 0, 8, 8, 0, true, false); + r0PositionQ = Calculation::qntzr(_rx->r0Position, 0, 17, 0, 0, true); + } + + RxParams(SonoDevice* device) : Register(BAR, OFFSET, device, LENGTH) + { + ADD_UNSIGNED_FIELD_LONG(rxActiveElementStep, RX_ACTIVE_ELEMENT_STEP_MASK); + ADD_UNSIGNED_FIELD_LONG(interceptPointFiringTime, INTERCEPT_POINT_FIRING_TIME_MASK); + ADD_UNSIGNED_FIELD_LONG(rxFocusPointNumber, RX_FOCUS_POINT_NUMBER_MASK); + ADD_UNSIGNED_FIELD_LONG(r0Position, R0_POSITION_MASK); + } }; #undef RX_ACTIVE_ELEMENT_STEP_MASK @@ -66,4 +68,4 @@ public: #undef OFFSET #undef LENGTH -#endif // RXPARAMS_H +#endif //RXPARAMS_H diff --git a/include/model/hardware/core/register/sram/registerDefinition/RxParamsDegree.h b/include/model/hardware/core/register/sram/registerDefinition/RxParamsDegree.h index 7e05b82..99f77ee 100644 --- a/include/model/hardware/core/register/sram/registerDefinition/RxParamsDegree.h +++ b/include/model/hardware/core/register/sram/registerDefinition/RxParamsDegree.h @@ -1,6 +1,7 @@ #ifndef RXPARAMSDEGREE_H #define RXPARAMSDEGREE_H +#include "model/scenarioGenerator/core/general/Calculation.h" #include "model/hardware/core/register/Register.h" #include "model/hardware/core/register/RegUtils.h" #include "SramStructures.h" @@ -20,20 +21,20 @@ class RxParamsDegree : public Register { private: SramRx* _rx; - QVector thetaCosQ; - QVector thetaSinQ; - QVector phiCosQ; - QVector phiSinQ; + QVector thetaCosQ; + QVector thetaSinQ; + QVector phiCosQ; + QVector phiSinQ; void prepareData(quint32 index) override { - thetaCos->setValueLong(thetaCosQ[static_cast(index)]); + thetaCos->setValueLong(static_cast(thetaCosQ[static_cast(index)])); - thetaSin->setValueLong(thetaSinQ[static_cast(index)]); + thetaSin->setValueLong(static_cast(thetaSinQ[static_cast(index)])); - phiCos->setValueLong(phiCosQ[static_cast(index)]) ; + phiCos->setValueLong(static_cast(phiCosQ[static_cast(index)])); - phiSin->setValueLong(phiSinQ[static_cast(index)]); + phiSin->setValueLong(static_cast(phiSinQ[static_cast(index)])); } public: @@ -45,10 +46,10 @@ public: void setRxParamsDegree (SramRx* rx) { _rx = rx; - thetaCosQ = Register::qntzr(_rx->thetaCos, 1, 16, 15, 0, true, true, true); - thetaSinQ = Register::qntzr(_rx->thetaSin, 1, 16, 15, 0, true, true, true); - phiCosQ = Register::qntzr(_rx->phiCos, 1, 16, 15, 0, true, true, true); - phiSinQ = Register::qntzr(_rx->phiSin, 1, 16, 15, 0, true, true, true); + thetaCosQ = Calculation::qntzr(_rx->thetaCos, 1, 16, 15, 0, true, true, true); + thetaSinQ = Calculation::qntzr(_rx->thetaSin, 1, 16, 15, 0, true, true, true); + phiCosQ = Calculation::qntzr(_rx->phiCos, 1, 16, 15, 0, true, true, true); + phiSinQ = Calculation::qntzr(_rx->phiSin, 1, 16, 15, 0, true, true, true); } RxParamsDegree(SonoDevice* device) : Register(BAR, OFFSET, device, LENGTH) diff --git a/include/model/hardware/core/register/sram/registerDefinition/RxParamsPos.h b/include/model/hardware/core/register/sram/registerDefinition/RxParamsPos.h index 8ab8ad1..e5b748a 100644 --- a/include/model/hardware/core/register/sram/registerDefinition/RxParamsPos.h +++ b/include/model/hardware/core/register/sram/registerDefinition/RxParamsPos.h @@ -1,6 +1,7 @@ #ifndef RXPARAMSPOS_H #define RXPARAMSPOS_H +#include "model/scenarioGenerator/core/general/Calculation.h" #include "model/hardware/core/register/Register.h" #include "model/hardware/core/register/RegUtils.h" #include "SramStructures.h" @@ -21,19 +22,19 @@ class RxParamsPos : public Register { private: SramRx* _rx; - QVector interceptXPosQ; - QVector interceptYPosQ; - QVector interceptZPosQ; + QVector interceptXPosQ; + QVector interceptYPosQ; + QVector interceptZPosQ; void prepareData(quint32 index) override { rxR0CenterActiveElementNumber->setValueLong(_rx->rxR0CenterActiveElementNumber[static_cast(index)] - 1); - interceptXPos->setValueLong(interceptXPosQ[static_cast(index)]); + interceptXPos->setValueLong(static_cast(interceptXPosQ[static_cast(index)])); - interceptYPos->setValueLong(interceptYPosQ[static_cast(index)]) ; + interceptYPos->setValueLong(static_cast(interceptYPosQ[static_cast(index)])); - interceptZPos->setValueLong(interceptZPosQ[static_cast(index)]); + interceptZPos->setValueLong(static_cast(interceptZPosQ[static_cast(index)])); } public: @@ -45,9 +46,9 @@ public: void setRxParamsPos (SramRx* rx) { _rx = rx; - interceptXPosQ = Register::qntzr(_rx->interceptXPos, 1, 18, 0, 0, true, true, true); - interceptYPosQ = Register::qntzr(_rx->interceptYPos, 1, 18, 0, 0, true, true, true); - interceptZPosQ = Register::qntzr(_rx->interceptZPos, 0, 17, 0, 0, true); + interceptXPosQ = Calculation::qntzr(_rx->interceptXPos, 1, 18, 0, 0, true, true, true); + interceptYPosQ = Calculation::qntzr(_rx->interceptYPos, 1, 18, 0, 0, true, true, true); + interceptZPosQ = Calculation::qntzr(_rx->interceptZPos, 0, 17, 0, 0, true); } RxParamsPos(SonoDevice* device) : Register(BAR, OFFSET, device, LENGTH) diff --git a/include/model/hardware/core/register/sram/registerDefinition/SoftwareMetaData.h b/include/model/hardware/core/register/sram/registerDefinition/SoftwareMetaData.h new file mode 100644 index 0000000..0c879ac --- /dev/null +++ b/include/model/hardware/core/register/sram/registerDefinition/SoftwareMetaData.h @@ -0,0 +1,43 @@ +#ifndef SOFTWAREMETADATA_H +#define SOFTWAREMETADATA_H + +#include "model/hardware/core/register/Register.h" +#include "model/hardware/core/register/RegUtils.h" + +#undef BAR + +#define META_DATA_MASK 0xFFFFFFFFFFFFFFFF + +#define BAR 1U +#define OFFSET 0x400000 +#define LENGTH 16U + +class SoftwareMetaData : public Register +{ +private: + QList _metaData; + void prepareData(quint32 index) override + { + metaData->setValueLong(_metaData[static_cast(index)]); + } + +public: + Field* metaData; + + void setSoftwareMetaData (QList& metaData) { + _metaData = metaData; + } + + SoftwareMetaData(SonoDevice* device) : Register(BAR, OFFSET, device, LENGTH) + { + ADD_UNSIGNED_FIELD_LONG(metaData, META_DATA_MASK); + } +}; + +#undef META_DATA_MASK + +#undef BAR +#undef OFFSET +#undef LENGTH + +#endif // SOFTWAREMETADATA_H diff --git a/include/model/hardware/core/register/sram/registerDefinition/TxParamsFocus.h b/include/model/hardware/core/register/sram/registerDefinition/TxParamsFocus.h index a4d8fb9..490423c 100644 --- a/include/model/hardware/core/register/sram/registerDefinition/TxParamsFocus.h +++ b/include/model/hardware/core/register/sram/registerDefinition/TxParamsFocus.h @@ -1,6 +1,7 @@ #ifndef TXPARAMSFOCUS_H #define TXPARAMSFOCUS_H +#include "model/scenarioGenerator/core/general/Calculation.h" #include "model/hardware/core/register/Register.h" #include "model/hardware/core/register/RegUtils.h" #include "SramStructures.h" @@ -19,17 +20,17 @@ class TxParamsFocus : public Register { private: SramTx* _tx; - QVector txFocusXPosQ; - QVector txFocusYPosQ; - QVector txFocusZPosQ; + QVector txFocusXPosQ; + QVector txFocusYPosQ; + QVector txFocusZPosQ; void prepareData(quint32 index) override { - txFocusXPos->setValueLong(txFocusXPosQ[static_cast(index)]); + txFocusXPos->setValueLong(static_cast(txFocusXPosQ[static_cast(index)])); - txFocusYPos->setValueLong(txFocusYPosQ[static_cast(index)]); + txFocusYPos->setValueLong(static_cast(txFocusYPosQ[static_cast(index)])); - txFocusZPos->setValueLong(txFocusZPosQ[static_cast(index)]) ; + txFocusZPos->setValueLong(static_cast(txFocusZPosQ[static_cast(index)])); } @@ -41,9 +42,9 @@ public: void setTxParamsFocus (SramTx* tx) { _tx = tx; - txFocusXPosQ = Register::qntzr(_tx->txFocusXPos, 1, 18, 0, 0, true, true, true); - txFocusYPosQ = Register::qntzr(_tx->txFocusYPos, 1, 18, 0, 0, true, true, true); - txFocusZPosQ = Register::qntzr(_tx->txFocusZPos, 0, 17, 0, 0, true); + txFocusXPosQ = Calculation::qntzr(_tx->txFocusXPos, 1, 18, 0, 0, true, true, true); + txFocusYPosQ = Calculation::qntzr(_tx->txFocusYPos, 1, 18, 0, 0, true, true, true); + txFocusZPosQ = Calculation::qntzr(_tx->txFocusZPos, 0, 17, 0, 0, true); } TxParamsFocus(SonoDevice* device) : Register(BAR, OFFSET, device, LENGTH) diff --git a/include/model/hardware/device/SonoConfig.h b/include/model/hardware/device/SonoConfig.h deleted file mode 100644 index e2bffce..0000000 --- a/include/model/hardware/device/SonoConfig.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef SONOADDRESS_H -#define SONOADDRESS_H - -#define BAR 2 - - -#define SW_BUFFER_NUM 100 -#define HW_BUFFER_NUM 16 -#define BUFFER_SIZE 4 * 1024 * 1024 - -#define COUNTER_REG 0x00002020 -//#define RAM_OFFSET_REG 0x00002024 -//#define XFER_OPT_REG 0x00002028 -//#define XFER_RATE_REG 0x0000202C -//#define CONTROL_REG 0x00000800 - -#define START_COMMAND 0x00000001 -#define STOP_COMMAND 0x00000000 - -#define COUNTER_MASK 0x0000001F - -//#define RAM_OFFSET_MASK 0x00FFFFFF - -//#define XFER_LEN_MASK 0x007FFFFF - -//#define AUTO_INC_COMMAND 0x40000000 - -//#define PERF_MODE_COMMAND 0x80000000 - -//#define XFER_RATE_MASK 0x003FFFFF - -#endif //SONOADDRESS_H diff --git a/include/model/hardware/device/SonoDevice.h b/include/model/hardware/device/SonoDevice.h index e2737ee..8eadde9 100644 --- a/include/model/hardware/device/SonoDevice.h +++ b/include/model/hardware/device/SonoDevice.h @@ -4,12 +4,12 @@ #include #include "SonoPcieDevice.h" -#include "SonoConfig.h" +#include "SonoDeviceConstant.h" class SonoDevice { private: - char* _buffers[SW_BUFFER_NUM]; + char* _buffers[SW_BUFFER_NUM]; public: SonoPcieDevice device; @@ -18,12 +18,11 @@ public: ~SonoDevice(); void init(); - void startDma(); - void stopDma(); + void startDma(); + void stopDma(); int getCounter(); - void copy(int srcIndex, int dstIndex); - //void show(int i); - const char* getBufferPtr(int index); + void copy(int srcIndex, int dstIndex); + const char* getBufferPtr(int index); }; #endif //SONODEVICE_H diff --git a/include/model/hardware/device/SonoDeviceConstant.h b/include/model/hardware/device/SonoDeviceConstant.h new file mode 100644 index 0000000..6326ead --- /dev/null +++ b/include/model/hardware/device/SonoDeviceConstant.h @@ -0,0 +1,35 @@ +#ifndef SONODEVICECONSTANT_H +#define SONODEVICECONSTANT_H + +#define BAR_REG 0 +#define BAR_SRAM 1 +#define BAR_BRAM 2 + +#define SW_BUFFER_NUM 100 +#define HW_BUFFER_NUM 16 +#define BUFFER_SIZE 4 * 1024 * 1024 + +#define COUNTER_REG 0x00002020 +#define RAM_OFFSET_REG 0x00002024 +#define XFER_OPT_REG 0x00002028 +#define XFER_RATE_REG 0x0000202C +#define CONTROL_REG 0x00000800 + +#define START_COMMAND 0x00000001 +#define STOP_COMMAND 0x00000000 + +#define COUNTER_MASK 0x0000001F + +#define RAM_OFFSET_MASK 0x00FFFFFF + +#define XFER_LEN_MASK 0x007FFFFF + +#define AUTO_INC_COMMAND 0x40000000 + +#define PERF_MODE_COMMAND 0x80000000 + +#define XFER_RATE_MASK 0x003FFFFF + +#define BUSY_MASK 0x80000000 + +#endif //SONODEVICECONSTANT_H diff --git a/include/model/hardware/exception/HardwareException.h b/include/model/hardware/exception/HardwareException.h new file mode 100644 index 0000000..0518389 --- /dev/null +++ b/include/model/hardware/exception/HardwareException.h @@ -0,0 +1,53 @@ +#ifndef HARDWAREEXCEPTION_H +#define HARDWAREEXCEPTION_H + +#include + +#include "logger/ESeverityLevel.h" +#include "model/hardware/exception/HwExceptionDef.h" + +class HardwareException : public std::exception +{ +private: + quint32 _errId; + QString _innerMessage; + +public: + explicit HardwareException(quint32 errId) + { + _errId = errId; + } + + explicit HardwareException(quint32 errId, QString innerMessage) + { + _errId = errId; + _innerMessage = innerMessage; + } + + const char* what() const noexcept override + { + return HwErrors::getErrorMessage(_errId).toStdString().c_str(); + } + + ESeverityLevel::eSeverityLevel getSeverityLevel() const + { + return HwErrors::getSeverityLevel(_errId); + } + + quint32 errId() const + { + return _errId; + } + + QString getInnerMessage() const + { + return _innerMessage; + } + + QString getMessage() const + { + return HwErrors::getErrorMessage(_errId); + } +}; + +#endif //HARDWAREEXCEPTION_H diff --git a/include/model/hardware/exception/HwExceptionDef.h b/include/model/hardware/exception/HwExceptionDef.h new file mode 100644 index 0000000..a0ec788 --- /dev/null +++ b/include/model/hardware/exception/HwExceptionDef.h @@ -0,0 +1,44 @@ +#ifndef HWEXCEPTIONDEF_H +#define HWEXCEPTIONDEF_H + +#include + +#include "logger/ESeverityLevel.h" + +#define HW_NOT_FOUND 0 +#define TRX_INIT_FAILED 1 +#define SLAVE_PROG_FAILED 2 + +struct HwErrors +{ + static QString getErrorMessage(quint32 id) + { + switch(id) + { + case HW_NOT_FOUND: + return + "No hardware was detected, please check your hardware is properly powered on and try again."; + + case TRX_INIT_FAILED: + return + "Could not init trx board."; + + case SLAVE_PROG_FAILED: + return + "Could not program slave FPGAs."; + } + } + + static ESeverityLevel::eSeverityLevel getSeverityLevel(quint32 id) + { + switch(id) + { + case HW_NOT_FOUND: + case TRX_INIT_FAILED: + case SLAVE_PROG_FAILED: + return ESeverityLevel::Error; + } + } +}; + +#endif //HWEXCEPTIONDEF_H diff --git a/include/model/hardware/service/BHardwarePacket.h b/include/model/hardware/service/BHardwarePacket.h new file mode 100644 index 0000000..96973fc --- /dev/null +++ b/include/model/hardware/service/BHardwarePacket.h @@ -0,0 +1,21 @@ +#ifndef BHARDWAREPACKET_H +#define BHARDWAREPACKET_H + +#include "model/hardware/service/HardwarePacket.h" + +class BHardwarePacket : public HardwarePacket +{ +private: + quint16 _totalBLineNumber; + quint16 _bPointNumber; + QByteArray _data; + int _index; + +public: + BHardwarePacket(); + + void decode(QByteArray buffer) override; + UsPacket getUsPacket(int fps) override; +}; + +#endif //BHARDWAREPACKET_H diff --git a/include/model/hardware/service/HardwarePacket.h b/include/model/hardware/service/HardwarePacket.h new file mode 100644 index 0000000..be9af68 --- /dev/null +++ b/include/model/hardware/service/HardwarePacket.h @@ -0,0 +1,29 @@ +#ifndef HARDWAREPACKET_H +#define HARDWAREPACKET_H + +#include + +#include "model/ultrasoundModule/UsPacket.h" +#include "model/hardware/service/PacketFormat.h" + +class HardwarePacket +{ +protected: + quint16 batch; + quint8 subBatch; + quint8 type; + quint8 frameCounter; + + quint16 Extract16BitValue(QByteArray buffer, int index); + +public: + HardwarePacket(); + virtual ~HardwarePacket() + { + } + + virtual void decode(QByteArray buffer); + virtual UsPacket getUsPacket(int fps) = 0; +}; + +#endif //HARDWAREPACKET_H diff --git a/include/model/hardware/service/HardwarePacketEngine.h b/include/model/hardware/service/HardwarePacketEngine.h new file mode 100644 index 0000000..fd4c5a1 --- /dev/null +++ b/include/model/hardware/service/HardwarePacketEngine.h @@ -0,0 +1,29 @@ +#ifndef HARDWAREPACKETENGINE_H +#define HARDWAREPACKETENGINE_H + +#include +#include + +#include "model/hardware/service/HardwarePacket.h" + +class HardwarePacketEngine : public QObject +{ + Q_OBJECT + +private: + HardwarePacket* _hardwarePacket; + qint32 _lastBatch; + QElapsedTimer _elapsedTimer; + + quint64 _start; + +public: + HardwarePacketEngine(); + + void newData(QByteArray buffer, bool flush = false); + +signals: + void newPacketReady(const UsPacket& packet); +}; + +#endif //HARDWAREPACKETENGINE_H diff --git a/include/model/hardware/service/PacketFormat.h b/include/model/hardware/service/PacketFormat.h new file mode 100644 index 0000000..d810bb9 --- /dev/null +++ b/include/model/hardware/service/PacketFormat.h @@ -0,0 +1,20 @@ +#ifndef PACKETFORMAT_H +#define PACKETFORMAT_H + +#define SOFTWARE_HEADER_LENGTH 128 + +#define BATCH_INDEX SOFTWARE_HEADER_LENGTH + 0 + +#define SUB_BATCH_INDEX SOFTWARE_HEADER_LENGTH + 2 + +#define TYPE_INDEX SOFTWARE_HEADER_LENGTH + 3 + +#define FRAME_COUNTER_INDEX SOFTWARE_HEADER_LENGTH + 4 + +#define B_LINE_NO_INDEX SOFTWARE_HEADER_LENGTH + 8 + +#define B_POINT_NO_INDEX SOFTWARE_HEADER_LENGTH + 10 + +#define PAYLOAD_INDEX SOFTWARE_HEADER_LENGTH + 32 + +#endif //PACKETFORMAT_H diff --git a/include/model/player/Player.h b/include/model/player/Player.h new file mode 100644 index 0000000..18971b8 --- /dev/null +++ b/include/model/player/Player.h @@ -0,0 +1,88 @@ +#ifndef PLAYER_H +#define PLAYER_H + +#include +#include + +#include "model/scenarioGenerator/ScenarioGenerator.h" +#include "model/player/dto/PlayerDisplayParameters.h" +#include "model/evocator/dto/CineDisplayParameters.h" +#include "viewModel/cine/setting/DataCineSetting.h" +#include "viewModel/cine/display/DataCineDisplay.h" +#include "model/backendImageProcessor/Bip.h" +#include "model/ultrasoundModule/UsModule.h" +#include "model/ultrasoundModule/UsData.h" +#include "model/player/core/PlayerCore.h" +#include "viewModel/MainViewModel.h" +#include "config/Configuration.h" + +/*************************************************************************************************/ +/** + * @brief This is a UsModule that playe scans. + * @author Mohammad Mohsen Talaie + * @details This module replay exam data for checking exam data after scan. + * @date 18 oct 2020 + */ +/*************************************************************************************************/ +class Player : public UsModule +{ + Q_OBJECT + US_MODULE + SINGLETON(Player) + +private: + PlayerCore* _core; + Player(); + + void prepareCoreForChangePlayOriginal(const DataCineSetting_t& dataCineSetting); + + void sendPlayerDisplayParametersToVM(const PlayerDisplayParameters_t& playerData); + + void updataOriginalPlay(const DataCineSetting_t& dataCineSetting); + + void updateSubClipStart(const DataCineSetting_t& dataCineSetting); + + void updateSubClipEnd(const DataCineSetting_t& dataCineSetting); + + void updateCinePlay(const DataCineSetting_t&); + + void updateRepeat(const DataCineSetting_t& dataCineSetting); + + void updateBSpeed(const DataCineSetting_t& dataCineSetting); + + void updateCoreCineSettingParameters(const DataCineSetting_t& dataCineSetting); + + bool checkOriginalPlayHasChanged(const DataCineSetting_t& dataCineSetting); + + bool checkDataCineSettingPlay(const DataCineSetting_t& dataCineSetting); + + bool checkIncomeSubClipStartHasChanged(const DataCineSetting_t& dataCineSetting); + + bool checkIncomeSubClipEndHasChanged(const DataCineSetting_t& dataCineSetting); + + bool checkIncomeCinePlayHasChanged(const DataCineSetting_t& dataCineSetting); + + bool checkDataCineSettingRepeatHasChanged(const DataCineSetting_t& dataCineSetting); + + bool checkIncomeBSpeedHasChanged(const DataCineSetting_t& dataCineSetting); + + bool checkCorePlayerIsFalse(); + + PlayerDisplayParameters_t preparePlayerDisplayParameters(const UsMetadataBag& metadataBag); + + PlayerDisplayParameters_t createPlayerDisplayParameters(const PlayerMetadata& playerMetadata); + +public: + ~Player() override; + +//uncrustify off +public slots: +//uncrustify on + void getUsPacketFromCore(const UsPacket& input); + + void getPlaySituation(const bool& play); + + void getBufferFromEvocator(QList > inputBuffer); +}; + +#endif //PLAYER_H diff --git a/include/model/player/core/PlayerCore.h b/include/model/player/core/PlayerCore.h new file mode 100644 index 0000000..a3c7e0b --- /dev/null +++ b/include/model/player/core/PlayerCore.h @@ -0,0 +1,130 @@ +#ifndef PLAYERCORE_H +#define PLAYERCORE_H + +#include +#include +#include +#include + +#include "model/ultrasoundModule/UsPacket.h" +#include "model/player/core/QueueReader.h" +#include "model/player/core/QueueWriter.h" +#include "model/player/type/EDirection.h" +#include "model/player/metadata/PlayerMetadata.h" +#include "model/ultrasoundModule/metadata/HardwareMetadata.h" +#include "model/evocator/metadata/EvocatorMetadata.h" +#include "model/evocator/dto/CineDisplayParameters.h" + +#define TIMES_OF_FPS 4 + +class PlayerCore : public QObject +{ + Q_OBJECT + +private: + static QMutex _locker; + QList > _buffer; + int _playerBufferSize; + int _currentSecond; + int _currentIndex; + int _subClipStart; + int _countOfFrame; + int _subClipEnd; + int _start = 0; + int _end; + int _step; + int _fps; + int _delay; + int _maxSecond; + float _bSpeed; + bool _playOriginal; + bool _resume; + bool _repeat; + bool _play; + bool _startOfPlay; + bool _fetchImage; + EDirection::eDirection _playDirection; + PlayerMetadata _metadata; + UsPacket* _playerBuffer; + QSemaphore _usedCells; + QSemaphore _freeCells; + QueueWriter _writer; + QueueReader _reader; + + void play(); + void stop(); + void pause(); + int calculateDelay(float speed); + void clearBuffer(); + void setWriterIndexToFirst(); + bool checkBufferHasData(); + bool checkCurrntIndesIsInBorders(bool includeStartEnd); + + void setStartAndEnd(int start, int end); + + void continuePlaying(); + + void continuePlaySubClip(); + + void findIndexForContinuePlaySubClip(); + +public: + float speedResource[4] = { 0.50F, 1.0F, 1.5F, 2.0F}; + PlayerCore(); + + ~PlayerCore(); + + void setPlayDirection(EDirection::eDirection playDirection); + void setBuffer(QList > buffer); + void setPlayOriginal(bool playOriginal); + void setSubClipStart(int input, int currentIndex); + void setSubClipEnd(int input, int currentIndex); + void setPlay(bool playInput); + void setResume(bool resume); + void setRepeat(bool repeat); + void fetchImage(int index); + void crawl(int diff); + void setBSpeed(int speed); + bool connection(); + + void preparePlayOriginalClip(); + + void preparePlaySubClip(); + + void initWriter(); + + void initReader(); + + void initPlayerParams(QList > buffer); + + void updateStep(); + + void stopAndClearBuffer(); + + bool getPlay() const; + + int getSubClipEnd() const; + + int getSubClipStart() const; + + bool getPlayOriginal() const; + + bool getRepeat() const; + + float getBSpeed() const; + + void clearPlayerBuffer(); + +signals: + void sendOutputPacket(const UsPacket& output); + void sendPlaySituation(const bool& play); + +//uncrustify off +public slots: +//uncrustify on + void getOutputPacket(const UsPacket& output); + void restartWriter(); + void restartReader(); +}; + +#endif //PLAYERCORE_H diff --git a/include/model/player/core/QueueReader.h b/include/model/player/core/QueueReader.h new file mode 100644 index 0000000..de0a7bf --- /dev/null +++ b/include/model/player/core/QueueReader.h @@ -0,0 +1,75 @@ +#ifndef QUEUEREADER_H +#define QUEUEREADER_H + +#include +#include +#include +#include +#include +#include + +#include "model/ultrasoundModule/UsPacket.h" + +/*****************************************************************************/ +/** + * @brief This class is reader part of player engine. This is a hook for player + * bufer and pull frame from player buffer and send that to Core. + * @author Mohammad Mohsen Talaie + * @date 14 nov 2020 + */ +/*****************************************************************************/ +class QueueReader : public QThread +{ + Q_OBJECT + +private: + static QElapsedTimer _timer; + static QMutex _locker; + + bool _reset = false; + bool* _play; + + int _circleBufferSize; + int _iteration; + int* _delay; + + UsPacket* _circleBuffer; + + QSemaphore* _usedCells; + QSemaphore* _freeCells; + +public: + QueueReader(QObject* parent = NULL) : QThread(parent) + { + } + + void initParams(QSemaphore* used, + QSemaphore* free, + UsPacket* circleBuffer, + const int circleBufferSize, + int* delay, + bool* play); + + void run() override; + + void Play(); + + void reset(); + + void resetIteration(); + + void setPlay(bool* play); + + void waitUntilPacketAvailable(); + + void watiForCompleteFPSCycleDlaye(); + + void waitUntilIncomePlayOrder(); + + void fetchImage(); + +signals: + void sendPacketToCore(const UsPacket& output); +}; + +#endif //QUEUEREADER_H diff --git a/include/model/player/core/QueueWriter.h b/include/model/player/core/QueueWriter.h new file mode 100644 index 0000000..1e5801c --- /dev/null +++ b/include/model/player/core/QueueWriter.h @@ -0,0 +1,99 @@ +#ifndef QUEUEWRITER_H +#define QUEUEWRITER_H + +#include +#include +#include +#include +#include + +#include "model/ultrasoundModule/UsPacket.h" +#include "model/player/metadata/PlayerMetadata.h" +#include "model/player/type/EDirection.h" +#include "model/ultrasoundModule/UsHelper.h" + +/*****************************************************************************/ +/** + * @brief This class is writer part of player engine. This class push frame + * into player buffer. + * @author Mohammad Mohsen Talaie + * @date 14 nov 2020 + */ +/*****************************************************************************/ +class QueueWriter : public QThread +{ + Q_OBJECT + SINGLETON(QueueWriter) + +private: + static QMutex _locker; + bool* _playOriginal; + bool _feedBuffer; + bool* _repeat; + bool* _play; + int _circleBufferSize; + int _iteration; + int* _start; + int _index; + int* _end; + int* _fps; + int* _step; + + EDirection::eDirection* _playDirection; + UsPacket* _circleBuffer; + QSemaphore* _usedCells; + QSemaphore* _freeCells; + QMutex* _bufferMutex; + const QList >* _buffer; + + UsPacket getPacketFromBuffer(); + + PlayerMetadata createPlayerMetadata(); + + void AppendMetaDataToPacket(UsPacket* packet, const PlayerMetadata& playerMetadata); + + void putPacketIntoCircleBuffer(const UsPacket& packet); + + void waitForPlayAndFeedBufferChanges(); + + void putPacketIntoQueue(); + + void fillCircleBuffer(); + + void updateIndex(); + + bool checkIndexBetweenBorders(); + +public: + QueueWriter(QObject* parent = NULL) : QThread(parent) + { + } + + void initParams(QSemaphore* used, + QSemaphore* free, + UsPacket* circleBuffer, + const int circleBufferSize, + const QList >* buffer, + int* step, + int* start, + int* end, + int* fps, + bool* play, + bool* playOriginal, + bool* repeat, + EDirection::eDirection* playMode); + + void run() override; + + void fetchImage(int index); + + void setFeedBuffer(const bool feedBuffer); + + void setIndex(int index); + + void resetIteration(); + + bool getFeedBuffer() const; +}; + +#endif //QUEUEWRITER_H diff --git a/include/model/player/dto/PlayerDisplayParameters.h b/include/model/player/dto/PlayerDisplayParameters.h new file mode 100644 index 0000000..8f2d84f --- /dev/null +++ b/include/model/player/dto/PlayerDisplayParameters.h @@ -0,0 +1,13 @@ +#ifndef PLAYERDISPLAYPARAMETERS_H +#define PLAYERDISPLAYPARAMETERS_H + +#include + +typedef struct PlayerDisplayParameters_t +{ + int index; + int second; +} PlayerDisplayParameters_t; +Q_DECLARE_METATYPE(PlayerDisplayParameters_t); + +#endif //PLAYERDISPLAYPARAMETERS_H diff --git a/include/model/player/metadata/PlayerMetadata.h b/include/model/player/metadata/PlayerMetadata.h new file mode 100644 index 0000000..1b4cd55 --- /dev/null +++ b/include/model/player/metadata/PlayerMetadata.h @@ -0,0 +1,20 @@ +#ifndef PLAYERMEATADATA_H +#define PLAYERMEATADATA_H + +#include +#include "model/ultrasoundModule/metadata/UsBaseMetadata.h" + +class PlayerMetadata : public UsBaseMetadata +{ +public: + PlayerMetadata(); + int currentScond = 0; + int currentIndex = 0; + int start = 0; + int end = 0; + bool orginalClip = true; +}; + +Q_DECLARE_METATYPE(PlayerMetadata) + +#endif //PLAYERMEATADATA_H diff --git a/include/model/player/type/EDirection.h b/include/model/player/type/EDirection.h new file mode 100644 index 0000000..eb11ef6 --- /dev/null +++ b/include/model/player/type/EDirection.h @@ -0,0 +1,35 @@ +#ifndef EPLAYMODE_H +#define EPLAYMODE_H + +#include +#include +#include + +class EDirection : public QObject +{ +private: + //Private constructor prevent the enumeration class from being instantiated + explicit EDirection(QObject* parent = nullptr); + +public: + enum eDirection : quint8 + { + forward = 0, + backward = 1, + forwardBackward = 2 + }; + Q_ENUM(eDirection) + + + static quint8 EnumToint(const eDirection qtEnum) + { + return QMetaEnum::fromType().value(qtEnum); + } + + static eDirection intToEnum(const quint8 intEnum) + { + return static_cast(intEnum); + } +}; + +#endif //EPLAYMODE_H diff --git a/include/model/scenarioGenerator/ScenarioGenerator.h b/include/model/scenarioGenerator/ScenarioGenerator.h new file mode 100644 index 0000000..98f85d8 --- /dev/null +++ b/include/model/scenarioGenerator/ScenarioGenerator.h @@ -0,0 +1,62 @@ +#ifndef SCENARIOGENERATOR_H +#define SCENARIOGENERATOR_H + +#include +#include +#include + +#include "model/ultrasoundModule/UsModule.h" +#include "model/scenarioGenerator/core/ScenGenCore.h" +#include "model/scenarioGenerator/core/ComputationalCore.h" +#include "model/databaseManager/type/EDatabaseRequest.h" + +/*************************************************************************************************/ +/** + * @brief This class is responsible for gathering user and system inputs and generate desired output + * for all of the system based on system provided algorithm + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2020/08/22(1399/6/1) + */ +/*************************************************************************************************/ +class ScenarioGenerator : public UsModule +{ + Q_OBJECT + US_MODULE + SINGLETON(ScenarioGenerator) + +private: + ScenGenCore* _core; + ComputationalCore* _computationalCore; + + ScenarioGenerator(); + ~ScenarioGenerator() override; + + ScenGenSystemParameters_t getSystemParameters(); + + void getApodization(ScenGenDatabase_t& database); + void getLpf(ScenGenDatabase_t& database); + void getLineFilter(ScenGenDatabase_t& database); + ScenGenDatabase_t getScenGenDatabase(); + + CommandResult requestDataFromDatabase(EDatabaseRequest::eDatabaseRequest request, + const QList args); + + template + T translateDatabaseData(const QList result); + + void sendScenGenSoftwareUpdateCommand(); + void processScenGenCommand(bool result, const CommandRequest& request); + +//uncrustify off +public slots: + void newSoftwareScenario(); + void newHardwareScenario(); + + void newAo(quint32 ao); + void newDtgc(QVector dtgc); + void newLineFilter(QVector lineFilter); + +//uncrustify on +}; + +#endif //SCENARIOGENERATOR_H diff --git a/include/model/scenarioGenerator/core/ComputationalCore.h b/include/model/scenarioGenerator/core/ComputationalCore.h new file mode 100644 index 0000000..a67a2d3 --- /dev/null +++ b/include/model/scenarioGenerator/core/ComputationalCore.h @@ -0,0 +1,71 @@ +#ifndef COMPUTATIONALCORE_H +#define COMPUTATIONALCORE_H + +#include +#include + +#include "model/scenarioGenerator/dto/software/SoftwareOutput.h" +#include "model/scenarioGenerator/dto/computational/ScenGenZoomGate.h" + +#define LINEAR_INIT_WIDTH 0.01F +#define LINEAR_INIT_DEPTH 0.01F +#define CONVEX_INIT_ANGLE 0.261799388F +#define CONVEX_INIT_DEPTH 0.025F +#define LINEAR_STEP 0.001F +#define CONVEX_LENGTH_STEP 0.01F +#define CONVEX_ANGLE_STEP 0.017453293F + +class ComputationalCore +{ +private: + ScenGenSoftwareOutput_t _softwareParams; + ScenGenScanConversionConfig_t _bScanConversion; + float _initAzimuthSize; + float _initAxialSize; + float _azimuthStep; + float _axialStep; + float _frameWidth; + float _frameDepth; + float _frameMinDepth; + float _frameMaxDepth; + bool _zoomON = false; + ScenGenZoomGate_t _zoomGate; + //init funttion + void init(); + void initZoomGate(); + void setZoomGateDefaults(); + void calculateGateDepth(float gateDepth); + void calculateMinMaxAzimuth(float gateWidth); + void calculateFrameSize(); + void setInitialSize(); + //change Size + bool canChangeAxialSize(int unit); + bool canChangeAzimuthSize(int unit); + bool isZoomGateAxialSurroundedInImage(int unit); + bool isZoomGateAzimuthSurroundedInImage(int unit); + void applyAxialSizeChange(int unit); + void applyAzimuthSizeChange(int unit); + //change Location + void changeGateLocation(int difX, int difZ, float azimuthStep, float axialStep); + bool canMinAzimuthLocChange(float location); + bool canMaxAzimuthLocChange(float location); + bool canMinAxialLocChange(float location); + bool canMaxAxialLocChange(float location); + void changeAzimuthLocation(float azimuthStep, int xUnit); + void changeAxialLocation(float axialStep, int zUnit); + //utilse + bool scanIsLinear(ScenGenScanConversionConfig_t& bScnConversion); + bool scanIsConvex(ScenGenScanConversionConfig_t& bScnConversion); + bool scanIsVirtualConvex(ScenGenScanConversionConfig_t& bScnConversion); + +public: + ComputationalCore(); + void setSoftwareParams(ScenGenSoftwareOutput_t& softwareParams); + void changeSize(int stepCount); + void changeLocation(int difX, int difZ); + ScenGenZoomGate_t getZoomGate(); + bool getZoomEnable(); + void zoomOff(); +}; + +#endif //COMPUTATIONALCORE_H diff --git a/include/model/scenarioGenerator/core/ScenGenCore.h b/include/model/scenarioGenerator/core/ScenGenCore.h new file mode 100644 index 0000000..72ba32b --- /dev/null +++ b/include/model/scenarioGenerator/core/ScenGenCore.h @@ -0,0 +1,100 @@ +#ifndef SCEN_GEN_CORE_H +#define SCEN_GEN_CORE_H + +#include + +#include "model/scenarioGenerator/dtoInternal/UserParameters.h" +#include "model/scenarioGenerator/dtoInternal/SystemParameters.h" +#include "model/scenarioGenerator/dtoInternal/ProbeParameters.h" +#include "model/scenarioGenerator/dto/software/SoftwareOutput.h" +#include "model/scenarioGenerator/dto/hardware/HardwareOutput.h" +#include "model/scenarioGenerator/dtoInternal/SystemParameters.h" +#include "model/scenarioGenerator/core/scenario/BaseScenario.h" +#include "model/scenarioGenerator/dtoInternal/ScenGenDatabase.h" +#include "model/backendImageProcessor/type/EImageMode.h" +#include "viewModel/bMode/setting/DataBModeSetting.h" +#include "viewModel/bMode/display/DataBModeDisplay.h" +#include "viewModel/tgc/DataTgc.h" +#include "viewModel/image/DataImage.h" +#include "model/scenarioGenerator/dto/computational/ScenGenZoomGate.h" + +/*************************************************************************************************/ +/** + * @brief This class is core of scenario generator and responsible for doing the actual job + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2020/08/22(1399/6/1) + */ +/*************************************************************************************************/ +class ScenGenCore : public QObject +{ + Q_OBJECT + +private: + ScenGenUserParameters_t _userParams; + ScenGenSoftwareOutput_t _softwareOutput; + ScenGenHardwareOutput_t _hardwareOutput; + ScenGenSystemParameters_t _systemParams; + ScenGenProbeParameters_t _probeParams; + + ScenGenDatabase_t _database; + + bool _isStarted; + + EImageMode::eImageMode _mode; + + bool _scenarioParamChanged; + bool _outputSizeParamChanged; + + void calculateScenarioDependentValues(); + void calculateScenarioIndependentSoftwareValues(); + + void calcSecondaryProbeProps(); + + BaseScenario* createScenario(); + +public: + ScenGenCore(); + + void process(); + void changeMode(EImageMode::eImageMode mode); + + void start(); + void stop(); + + void updateModeBSettingParams(DataBModeSetting_t setting); + void updateModeBDisplayParams(DataBModeDisplay_t setting); + void updateTgcParams(DataTgc_t setting); + void updateImageParams(DataImage_t setting); + + void updateDatabase(ScenGenDatabase_t database); + + void calculateStbValues(); + void calculateAoValues(); + void calculateLineFilterValues(); + void calculateAtgcValues(); + void calculateLpfValues(); + void calculateApodizationValues(); + void calculateDtgcValues(); + + void updateRegs(); + + void calculateScanConvValues(); + + void updateHDZoomGate(ScenGenZoomGate_t zoomGate); + + void setProbeParameters(ScenGenProbeProperties_t value); + void setSystemParameters(ScenGenSystemParameters_t value); + + ScenGenSoftwareOutput_t getSoftwareValues(); + ScenGenSoftwareOutput_t getHardwareValues(); + +signals: + void softwareScenarioReady(); + void hardwareScenarioReady(); + + void aoReady(int ao); + void dtgcReady(QVector dtgc); + void lineFilterReady(QVector lineFilter); +}; + +#endif //SCEN_GEN_CORE_H diff --git a/include/model/scenarioGenerator/core/general/AperturePosition.h b/include/model/scenarioGenerator/core/general/AperturePosition.h new file mode 100644 index 0000000..7df91eb --- /dev/null +++ b/include/model/scenarioGenerator/core/general/AperturePosition.h @@ -0,0 +1,140 @@ +#ifndef APERTUREPOSITION_H +#define APERTUREPOSITION_H + +#include + +#include +#include + +#include "model/scenarioGenerator/core/general/Calculation.h" +#include "model/scenarioGenerator/dtoInternal/ProbeParameters.h" + +struct Apertureposition +{ +private: + float pitchAzimuth; + QVector elementAzimuth; + qint32 elementNo; + + QVector interceptAzimuth; + + QVector centerActiveElementNo; + QVector startActiveElementNo; + + QVector activeElementNo; + + void init(ScenGenProbeParameters_t probe, QVector activeElemNo, QList points) + { + pitchAzimuth = probe.getScndProbeProps().pitchAzimuth; + elementAzimuth = probe.getScndProbeProps().elementAzimuth; + elementNo = probe.getProbeProps().elementNo; + + for(auto i = 0; i < points.length(); i++) + { + interceptAzimuth.push_back(points[i].azimuth); + } + + activeElementNo = activeElemNo; + } + + qint32 getCurrentCenterActiveElementNo(float activeElement) + { + auto currentCenterActiveElementNo = static_cast(round(activeElement)); + if(currentCenterActiveElementNo < 1) + { + currentCenterActiveElementNo = 1; + } + else if(currentCenterActiveElementNo > elementNo) + { + currentCenterActiveElementNo = elementNo; + } + + return currentCenterActiveElementNo; + } + + qint32 getCenterElementFlag(float activeElement) + { + return activeElement - floorf(activeElement) == 0.5f ? 1 : 0; + } + + qint32 getCenterFlag(qint32 currentCenterActiveElementNo, qint32 index) + { + return elementAzimuth[currentCenterActiveElementNo - 1] <= interceptAzimuth[index] ? 1 : 0; + } + + float getPreElementNo(qint32 currentCenterActiveElementNo, qint32 index) + { + auto preElementNo = currentCenterActiveElementNo - floorf(activeElementNo[index] / 2); + + if(activeElementNo[index] % 2 == 0) + { + auto centerFlag = getCenterFlag(currentCenterActiveElementNo, index); + preElementNo -= centerFlag; + } + else + { + preElementNo -= 1; + } + + return preElementNo; + } + + void checkElement(qint32* currentCenterActiveElementNo, float* preElementNo, qint32 index) + { + if(*preElementNo < 0) + { + *preElementNo = 0; + *currentCenterActiveElementNo = + static_cast(floorf(activeElementNo[index] / 2) + 1); + } + + if(elementNo - *preElementNo - activeElementNo[index] < 0) + { + *preElementNo = elementNo - activeElementNo[index]; + *currentCenterActiveElementNo = + static_cast(elementNo - floorf(activeElementNo[index] / 2)); + } + } + + float getStartActive(float preElementNo, qint32 centerElementFlag) + { + auto startActive = preElementNo + 1 - centerElementFlag; + if(startActive < 1) + { + startActive = 1; + } + + return startActive; + } + +public: + QPair, QVector > getAperturePosition(ScenGenProbeParameters_t probe, + QVector activeElemNo, + QList points) + { + init(probe, activeElemNo, points); + + for(auto i = 0; i < activeElementNo.length(); i++) + { + auto centerActiveElement = interceptAzimuth[i] / pitchAzimuth + (elementNo + 1.0f) / 2; + + auto currentCenterActiveElementNo = + getCurrentCenterActiveElementNo(centerActiveElement); + + auto preElementNo = getPreElementNo(currentCenterActiveElementNo, i); + + checkElement(¤tCenterActiveElementNo, &preElementNo, i); + + auto centerElementFlag = getCenterElementFlag(centerActiveElement); + auto startActive = getStartActive(preElementNo, centerElementFlag); + + centerActiveElementNo.push_back(static_cast(currentCenterActiveElementNo - 1)); + startActiveElementNo.push_back(static_cast(startActive - 1)); + } + + return QPair, QVector >(startActiveElementNo, + centerActiveElementNo); + } +}; + +#endif //APERTUREPOSITION_H diff --git a/include/model/scenarioGenerator/core/general/BlendCoeff.h b/include/model/scenarioGenerator/core/general/BlendCoeff.h new file mode 100644 index 0000000..1510ef7 --- /dev/null +++ b/include/model/scenarioGenerator/core/general/BlendCoeff.h @@ -0,0 +1,239 @@ +#ifndef BLENDCOEFF_H +#define BLENDCOEFF_H + +#include + +#include +#include + +#include "model/scenarioGenerator/dtoInternal/UserParameters.h" +#include "model/scenarioGenerator/dtoInternal/ProbeParameters.h" +#include "model/scenarioGenerator/core/general/Calculation.h" + +struct BlendCoeff +{ +private: + quint8 focusNo; + bool ffc; + quint8 focus; + float depth; + bool hi; + + QList focusValues; + QList hiFocusValues; + quint32 multiFocusStep; + QList > ffcValues; + + quint32 rxFocuspointNo; + float pointDax; + QList shotWeight; + + QVector > blendWeight; + QVector blendPos; + + void fillBlendWeightWithZero() + { + for(auto i = 0; i < 512; i++) + { + QVector temp; + for(auto j = 0; j < 4; j++) + { + temp.push_back(0); + } + blendWeight.push_back(temp); + } + } + + void fillBlendWeightFirstColumnWithOne() + { + for(auto i = 0; i < blendWeight.length(); i++) + { + blendWeight[i][0] = 1; + } + } + + void appendToBlendPos(float value) + { + if(!(value <= depth)) + { + return; + } + + value = roundf(value / pointDax) + 1; + + value = ceilf(value / 16); + + blendPos.push_back(value); + } + + void prepareBlendPos() + { + blendPos.push_front(0); + blendPos.push_back(ceilf(rxFocuspointNo / 16.0f)); + } + + void getBlendPosForFfc() + { + auto temp = (ffcValues[0][focus] + ffcValues[1][focus]) / 2; + appendToBlendPos(temp); + prepareBlendPos(); + } + + void getBlendPosForHi() + { + for(auto i = 1; i <= focusNo - 1; i++) + { + auto temp = + (hiFocusValues[focus + i * multiFocusStep] + + hiFocusValues[focus + (i - 1) * multiFocusStep]) / 2; + + appendToBlendPos(temp); + } + + prepareBlendPos(); + } + + void getBlendPosForNoneHi() + { + for(auto i = 1; i <= focusNo - 1; i++) + { + auto temp = + (focusValues[focus + i * multiFocusStep] + + focusValues[focus + (i - 1) * multiFocusStep]) / 2; + appendToBlendPos(temp); + } + + prepareBlendPos(); + } + + QVector diffBlendPos() + { + QVector temp; + for(auto i = 0; i < blendPos.length() - 1; i++) + { + temp.push_back(blendPos[i + 1] - blendPos[i]); + } + + return temp; + } + + void calcBlendWeightForMultiFocus() + { + if(ffc) + { + getBlendPosForFfc(); + } + else if(hi) + { + getBlendPosForHi(); + } + else + { + getBlendPosForNoneHi(); + } + + if(blendPos.length() > 2) + { + auto shotLength = diffBlendPos(); + + for(auto i = 1; i < blendPos.length(); i++) + { + auto smoothDepth = static_cast(roundf(shotLength[i - 1] / 10.0f)); + auto smoothWeight = Calculation::linearSpace(1, 0.5f, smoothDepth); + if(i == 1) + { + for(auto r = blendPos[i - 1]; r < blendPos[i] - smoothDepth; r++) + { + blendWeight[r][i - 1] = shotWeight[i - 1]; + } + auto k = 0; + for(auto r = blendPos[i] - smoothDepth; r < blendPos[i]; r++) + { + blendWeight[r][i - 1] = smoothWeight[k] * shotWeight[i - 1]; + blendWeight[r][i] = (1 - smoothWeight[k]) * shotWeight[i]; + k++; + } + } + else if(i == blendPos.length() - 1) + { + auto k = 0; + for(auto r = blendPos[i - 1]; r < blendPos[i - 1] + smoothDepth; r++) + { + blendWeight[r][i - 2] = (smoothWeight[k] - 0.5f) * shotWeight[i - 2]; + blendWeight[r][i - 1] = (1.5f - smoothWeight[k]) * shotWeight[i - 1]; + k++; + } + for(auto r = blendPos[i - 1] + smoothDepth; r < blendPos[i]; r++) + { + blendWeight[r][i - 1] = shotWeight[i - 1]; + } + } + else + { + auto k = 0; + for(auto r = blendPos[i - 1]; r < blendPos[i - 1] + smoothDepth; r++) + { + blendWeight[r][i - 2] = (smoothWeight[k] - 0.5f) * shotWeight[i - 2]; + blendWeight[r][i - 1] = (1.5f - smoothWeight[k]) * shotWeight[i - 1]; + k++; + } + for(auto r = blendPos[i - 1] + smoothDepth; + r < blendPos[i] - smoothDepth; + r++) + { + blendWeight[r][i - 1] = shotWeight[i - 1]; + } + k = 0; + for(auto r = blendPos[i] - smoothDepth; r < blendPos[i]; r++) + { + blendWeight[r][i - 1] = smoothWeight[k] * shotWeight[i - 1]; + blendWeight[r][i] = (1 - smoothWeight[k]) * shotWeight[i]; + k++; + } + } + } + } + else + { + fillBlendWeightFirstColumnWithOne(); + } + } + +public: + QVector > getBlendWeight(ScenGenUserParameters_t input, + ScenGenProbeParameters_t probe, + quint32 rxFocuspointNo, + float pointDax, + QList shotWeight) + { + focusNo = input.focusNumber; + ffc = input.focusFrequencyCompound; + focus = input.focus; + depth = input.depth; + hi = input.harmonicImaging; + + focusValues = probe.getProbeProps().focusValues; + hiFocusValues = probe.getProbeProps().hiFocusValues; + ffcValues = probe.getProbeProps().ffcValues; + multiFocusStep = probe.getProbeProps().multiFocusStep; + + this->rxFocuspointNo = rxFocuspointNo; + this->pointDax = pointDax; + this->shotWeight = shotWeight; + + fillBlendWeightWithZero(); + + if(focusNo > 1) + { + calcBlendWeightForMultiFocus(); + } + else + { + fillBlendWeightFirstColumnWithOne(); + } + + return blendWeight; + } +}; + +#endif //BLENDCOEFF_H diff --git a/include/model/scenarioGenerator/core/general/Calculation.h b/include/model/scenarioGenerator/core/general/Calculation.h new file mode 100644 index 0000000..9e5846d --- /dev/null +++ b/include/model/scenarioGenerator/core/general/Calculation.h @@ -0,0 +1,112 @@ +#ifndef CALCULATIONS_H +#define CALCULATIONS_H + +#include "model/scenarioGenerator/dtoInternal/ProbeParameters.h" +#include "model/scenarioGenerator/dtoInternal/UserParameters.h" +#include "model/scenarioGenerator/core/scenario/type/misc/Pulse.h" +#include "model/scenarioGenerator/core/scenario/type/misc/Point.h" + +/*************************************************************************************************/ +/** + * @brief Contains algorithms used accross all modes + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2020/08/22(1399/6/1) + */ +/*************************************************************************************************/ +class Calculation +{ +public: + Calculation(); + + static QVector lag(int pulseTypeNo, QList pulseProps, + QVector impulseResponse); + + static QVector convolution(QVector input1, QVector input2); + + static QPair linearSpaceDistance(float interval, + float distance, + quint32 maxSampleNo); + static QPair linearSpaceInterval(float interval, + float distance, + quint32 maxSampleNo); + static QPair linearSpaceSampleNo(float interval, + quint32 maxSampleNo); + + static QVector linearSpace(float start, float end, quint32 sampleNo); + + static QPair, QVector > aperturePosition( + ScenGenProbeParameters_t probe, + QVector activeElementNo, + QList points); + + static QVector > blendCoeff(ScenGenUserParameters_t input, + ScenGenProbeParameters_t probe, + quint32 rxFocuspointNo, + float pointDax, + QList shotWeight); + + static QVector qntzr(QVector data, + quint32 sign, + quint32 wordlength, + quint32 fractionalLength, + float maxLevel, + bool integerOutput, + bool useRound = true, + bool twosCmpl = false); + + static QVector calcDtgcLut(QList dtgcSlider, + float dtgcLen, + float maxWeight); + + template static QVector repElem(QVector input, quint32 number) + { + QVector temp; + for(auto i = 0U; i < input.length(); i++) + { + for(auto j = 0U; j < number; j++) + { + temp.push_back(input[i]); + } + } + + return temp; + } + + template static QVector repMat(QVector input, quint32 number) + { + QVector temp; + for(auto i = 0U; i < number; i++) + { + for(auto j = 0; j < input.length(); j++) + { + temp.push_back(input[j]); + } + } + + return temp; + } + + template static QVector zeros(quint32 length) + { + QVector temp; + for(auto i = 0U; i < length; i++) + { + temp.push_back(0); + } + + return temp; + } + + template static QVector ones(quint32 length) + { + QVector temp; + for(auto i = 0U; i < length; i++) + { + temp.push_back(1); + } + + return temp; + } +}; + +#endif //CALCULATIONS_H diff --git a/include/model/scenarioGenerator/core/general/InterceptFocus.h b/include/model/scenarioGenerator/core/general/InterceptFocus.h new file mode 100644 index 0000000..c5af255 --- /dev/null +++ b/include/model/scenarioGenerator/core/general/InterceptFocus.h @@ -0,0 +1,219 @@ +#ifndef INTERCEPTFOCUS_H +#define INTERCEPTFOCUS_H + +#include + +#include +#include + +#include "model/scenarioGenerator/dtoInternal/ProbeParameters.h" +#include "model/scenarioGenerator/core/scenario/type/misc/Point.h" +#include "model/scenarioGenerator/core/general/Calculation.h" + +struct InterceptFocus +{ +private: + ScenGenProbeParameters_t _probe; + QVector _interceptAz; + QVector _focusR; + float _steering; + float _dr; + + bool isProbeLinear() + { + return _probe.getProbeProps().linear; + } + + bool isVirtualConvex() + { + return _probe.getScndProbeProps().vcMaxTheta > 0; + } + + QPair fillPoints(float theta, + float x, + float y, + float z, + float focusAz, + float interceptAz, + float focusR) + { + Point_t intercept; + Point_t focus; + + auto focusXPos = x + focusR * sinf(theta) / _dr; + auto focusYPos = 0; + auto focusZPos = z + focusR * cosf(theta) / _dr; + + intercept.x = x; + intercept.y = y; + intercept.z = z; + intercept.azimuth = interceptAz; + intercept.theta = theta; + + focus.x = focusXPos; + focus.y = focusYPos; + focus.z = focusZPos; + focus.r = focusR; + focus.azimuth = focusAz; + focus.theta = theta; + + return QPair(intercept, focus); + } + + float getFocusR(int index) + { + float focusR; + if(_focusR.length() == 1) + { + focusR = _focusR[0]; + } + else + { + focusR = _focusR[index]; + } + + return focusR; + } + + QPair, QList > calcInterceptFocusForLinearProbe() + { + QList intercept; + QList focus; + for(auto i = 0; i < _interceptAz.length(); i++) + { + auto theta = _steering; + + auto interceptXPos = _interceptAz[i] / _dr; + auto interceptYPos = 0.0f; + auto interceptZPos = 0.0f; + + auto focusR = getFocusR(i); + + auto focusAzimuth = _interceptAz[i] + focusR * sinf(_steering); + + auto interceptAzimuth = _interceptAz[i]; + + auto res = fillPoints(theta, + interceptXPos, + interceptYPos, + interceptZPos, + focusAzimuth, + interceptAzimuth, + focusR); + + intercept.append(res.first); + focus.append(res.second); + } + + return QPair, QList >(intercept, focus); + } + + QPair, QList > calcInterceptFocusForVirtualConvexProbe() + { + auto virtualOriginalZ = _probe.getScndProbeProps().virtualOriginalZ; + + QList intercept; + QList focus; + for(auto i = 0; i < _interceptAz.length(); i++) + { + auto theta = _interceptAz[i] + _steering; + + auto interceptAzimuth = tanf(_interceptAz[i]) * virtualOriginalZ; + + auto interceptXPos = interceptAzimuth / _dr; + auto interceptYPos = 0.0f; + auto interceptZPos = 0.0f; + + auto focusR = getFocusR(i); + + auto focusAzimuth = tanf(_interceptAz[i]) * virtualOriginalZ + focusR * sinf(theta); + + auto res = fillPoints(theta, + interceptXPos, + interceptYPos, + interceptZPos, + focusAzimuth, + interceptAzimuth, + focusR); + + intercept.append(res.first); + focus.append(res.second); + } + + return QPair, QList >(intercept, focus); + } + + QPair, QList > calcInterceptFocusForConvexProbe() + { + auto radius = _probe.getProbeProps().radius; + auto virtualOriginalZ = _probe.getScndProbeProps().virtualOriginalZ; + auto correctionZ = _probe.getScndProbeProps().correctionZ; + + QList intercept; + QList focus; + for(auto i = 0; i < _interceptAz.length(); i++) + { + auto theta = atan2f(radius * sinf(_interceptAz[i]), + radius * cosf(_interceptAz[i]) - virtualOriginalZ) + _steering; + + auto interceptXPos = sinf(_interceptAz[i]) * radius / _dr; + auto interceptYPos = 0.0f; + auto interceptZPos = cosf(_interceptAz[i]) * radius / _dr + correctionZ; + + auto focusR = getFocusR(i); + + auto focusAzimuth = atan2f(sinf(_interceptAz[i]) * radius + sinf(theta) * focusR, + cosf(_interceptAz[i]) * radius + cosf(theta) * focusR); + + auto interceptAzimuth = _interceptAz[i]; + + auto res = fillPoints(theta, + interceptXPos, + interceptYPos, + interceptZPos, + focusAzimuth, + interceptAzimuth, + focusR); + + intercept.append(res.first); + focus.append(res.second); + } + + return QPair, QList >(intercept, focus); + } + +public: + InterceptFocus(ScenGenProbeParameters_t probe, + QVector interceptAz, + QVector focusR, + float steering, + float dr) + { + _probe = probe; + _interceptAz = interceptAz; + _focusR = focusR; + _steering = steering; + _dr = dr; + } + + QPair, QList > getInterceptFocus() + { + if(isProbeLinear()) + { + if(isVirtualConvex()) + { + return calcInterceptFocusForVirtualConvexProbe(); + } + else + { + return calcInterceptFocusForLinearProbe(); + } + } + else + { + return calcInterceptFocusForConvexProbe(); + } + } +}; + +#endif //INTERCEPTFOCUS_H diff --git a/include/model/scenarioGenerator/core/general/MinMaxDelay.h b/include/model/scenarioGenerator/core/general/MinMaxDelay.h new file mode 100644 index 0000000..698b30c --- /dev/null +++ b/include/model/scenarioGenerator/core/general/MinMaxDelay.h @@ -0,0 +1,175 @@ +#ifndef MINMAXDELAY_H +#define MINMAXDELAY_H + +#include + +#include +#include + +#include "model/scenarioGenerator/dtoInternal/ProbeParameters.h" +#include "model/scenarioGenerator/core/scenario/type/misc/Point.h" +#include "model/scenarioGenerator/core/scenario/type/misc/Aperture.h" +#include "model/scenarioGenerator/core/scenario/type/misc/Delay.h" +#include "model/scenarioGenerator/core/general/Calculation.h" +#include "model/backendImageProcessor/core/algorithm/ScanConversionAlg.h" + +struct MinMaxDelayResponse +{ + QVector minDelay; + QVector maxDelay; + QVector minDelayQ; + QVector maxDelayQ; +}; + +struct MinMaxDelay +{ +private: + ScenGenProbeParameters_t _probe; + Aperture_t _aperture; + QList _focusPoint; + +public: + MinMaxDelay(ScenGenProbeParameters_t probe, Aperture_t aperture, QList focusPoint) + { + _probe = probe; + _aperture = aperture; + _focusPoint = focusPoint; + } + + MinMaxDelayResponse getMinMaxDelay() + { + auto elementXPositionQ = Calculation::qntzr(_probe.getScndProbeProps().elementXPosition, + 1, + 18, + 0, + 0, + true, + true); + auto elementYPositionQ = Calculation::qntzr(_probe.getScndProbeProps().elementYPosition, + 1, + 18, + 0, + 0, + true, + true); + auto elementZPositionQ = Calculation::qntzr(_probe.getScndProbeProps().elementZPosition, + 0, + 17, + 0, + 0, + true, + true); + + QVector focusXPos; + QVector focusYPos; + QVector focusZPos; + QVector focusAz; + + for(auto i = 0; i < _focusPoint.length(); i++) + { + focusXPos.append(_focusPoint[i].x); + focusYPos.append(_focusPoint[i].y); + focusZPos.append(_focusPoint[i].z); + focusAz.append(_focusPoint[i].azimuth); + } + + auto focusXPosQ = Calculation::qntzr(focusXPos, 1, 18, 0, 0, true, true); + auto focusYPosQ = Calculation::qntzr(focusYPos, 1, 18, 0, 0, true, true); + auto focusZPosQ = Calculation::qntzr(focusZPos, 0, 17, 0, 0, true, true); + + QVector aprFirstEl; + for(auto i = 0; i < _aperture.startActiveElementNumber.length(); i++) + { + aprFirstEl.push_back(_aperture.startActiveElementNumber[i]); + } + + QVector aprLastEl; + for(auto i = 0; i < _aperture.startActiveElementNumber.length(); i++) + { + aprLastEl.append( + _aperture.startActiveElementNumber[i] + _aperture.activeElementNumber[i] - 1); + } + + QVector minDelayElementNo; + for(auto i = 0; i < focusAz.length(); i++) + { + auto t = focusAz[i] / _probe.getScndProbeProps().pitchAzimuth + + (_probe.getProbeProps().elementNo + 1) / 2.0f; + auto temp = + static_cast(roundf(t)); + + if(temp < aprFirstEl[i] + 1) + { + temp = aprFirstEl[i] + 1; + } + + if(temp > aprLastEl[i] + 1) + { + temp = aprLastEl[i] + 1; + } + + temp = temp > 0 ? temp - 1 : temp; + minDelayElementNo.append(temp); + } + + MinMaxDelayResponse delay; + + auto elementXPosition = _probe.getScndProbeProps().elementXPosition; + auto elementYPosition = _probe.getScndProbeProps().elementYPosition; + auto elementZPosition = _probe.getScndProbeProps().elementZPosition; + + for(auto i = 0; i < minDelayElementNo.length(); i++) + { + auto temp = sqrtf(powf(focusXPos[i] - elementXPosition[minDelayElementNo[i]], 2.0f) + + powf(focusYPos[i] - elementYPosition[minDelayElementNo[i]], 2.0f) + + powf(focusZPos[i] - elementZPosition[minDelayElementNo[i]], 2.0f)); + + delay.minDelay.append(temp); + + temp = sqrtf(powf(focusXPosQ[i] - elementXPositionQ[minDelayElementNo[i]], 2.0f) + + powf(focusYPosQ[i] - elementYPositionQ[minDelayElementNo[i]], 2.0f) + + powf(focusZPosQ[i] - elementZPositionQ[minDelayElementNo[i]], 2.0f)); + + delay.minDelayQ.append(temp); + } + + auto elementAz = _probe.getScndProbeProps().elementAzimuth; + for(auto i = 0; i < aprFirstEl.length(); i++) + { + auto centerAz = (elementAz[aprFirstEl[i]] + elementAz[aprLastEl[i]]) / 2; + if(centerAz < focusAz[i]) + { + auto temp = sqrtf(powf(focusXPos[i] - elementXPosition[aprFirstEl[i]], 2.0f) + + powf(focusYPos[i] - elementYPosition[aprFirstEl[i]], 2.0f) + + powf(focusZPos[i] - elementZPosition[aprFirstEl[i]], 2.0f)); + + delay.maxDelay.append(temp); + + temp = roundf(sqrtf(powf(focusXPosQ[i] - elementXPositionQ[aprFirstEl[i]], 2.0f) + + powf(focusYPosQ[i] - elementYPositionQ[aprFirstEl[i]], 2.0f) + + powf(focusZPosQ[i] - elementZPositionQ[aprFirstEl[i]], 2.0f))); + + delay.maxDelayQ.push_back(static_cast(temp)); + } + else + { + auto temp = sqrtf(powf(focusXPos[i] - elementXPosition[aprLastEl[i]], 2.0f) + + powf(focusYPos[i] - elementYPosition[aprLastEl[i]], 2.0f) + + powf(focusZPos[i] - elementZPosition[aprLastEl[i]], 2.0f)); + + delay.maxDelay.append(temp); + + temp = + roundf(sqrtf(powf(focusXPosQ[i] - elementXPositionQ[aprLastEl[i]], 2) + + powf(focusYPosQ[i] - elementYPositionQ[aprLastEl[i]], 2) + + powf(focusZPosQ[i] - elementZPositionQ[aprLastEl[i]], 2))); + + delay.maxDelayQ.push_back(static_cast(temp)); + } + } + + return delay; + } +}; + +#endif //MINMAXDELAY_H diff --git a/include/model/scenarioGenerator/core/general/ScenGenReceiverConfigurationProperties.h b/include/model/scenarioGenerator/core/general/ScenGenReceiverConfigurationProperties.h new file mode 100644 index 0000000..05aca9d --- /dev/null +++ b/include/model/scenarioGenerator/core/general/ScenGenReceiverConfigurationProperties.h @@ -0,0 +1,21 @@ +#ifndef SCENGENRECEIVERCONFIGURATIONPROPERTIES_H +#define SCENGENRECEIVERCONFIGURATIONPROPERTIES_H + +#include + +typedef struct ScenGenReceiverConfigurationProperties_t { + quint32 multiLineAcquisition; + quint32 lineMode; + quint32 atgcSelector; + bool syntheticTransmitBeamEnable; + quint32 syntheticTransmitBeam; + bool subtractFilterEnable; + bool dcCancelEnable; + quint32 ncoFrequencySelector; + quint32 lowPassFilterSelector; + bool absoluteUnitEnable; + quint32 focusNo; + bool lineFilterEnable; +}ScenGenReceiverConfigurationProperties_t; + +#endif //SCENGENRECEIVERCONFIGURATIONPROPERTIES_H diff --git a/include/model/scenarioGenerator/core/scenario/B/BModeScenario.h b/include/model/scenarioGenerator/core/scenario/B/BModeScenario.h new file mode 100644 index 0000000..9f7db96 --- /dev/null +++ b/include/model/scenarioGenerator/core/scenario/B/BModeScenario.h @@ -0,0 +1,30 @@ +#ifndef BMODESCENARIO_H +#define BMODESCENARIO_H + +#include "model/scenarioGenerator/core/scenario/BaseScenario.h" + +class BModeScenario : public BaseScenario +{ +private: + +protected: + void initRegisterSpace() override; + void calcFrameParameters() override; + void calcPulseIntervalFrameRate() override; + void calcIndexParameters() override; + void calcPulseProperties() override; + void calcRxBeamFormerProperties() override; + void calcReceiverConfigProperties() override; + void calcFreqLut() override; + +public: + BModeScenario(ScenGenUserParameters_t userParam, + ScenGenSystemParameters_t sysParam, + ScenGenProbeParameters_t probeParam); + + ~BModeScenario() override + { + } +}; + +#endif //BMODESCENARIO_H diff --git a/include/model/scenarioGenerator/core/scenario/BaseScenario.h b/include/model/scenarioGenerator/core/scenario/BaseScenario.h new file mode 100644 index 0000000..f703d2e --- /dev/null +++ b/include/model/scenarioGenerator/core/scenario/BaseScenario.h @@ -0,0 +1,64 @@ +#ifndef BASESCENARIO_H +#define BASESCENARIO_H + +#include "model/scenarioGenerator/dtoInternal/UserParameters.h" +#include "model/scenarioGenerator/dtoInternal/SystemParameters.h" +#include "model/scenarioGenerator/dtoInternal/ProbeParameters.h" +#include "model/scenarioGenerator/dto/software/SoftwareOutput.h" +#include "model/scenarioGenerator/dto/hardware/HardwareOutput.h" +#include "model/scenarioGenerator/core/scenario/type/frame/BaseFrame.h" + +class BaseScenario +{ +private: + void calcBlendLut(); + void calcElementPositionLut(); + void calcScenarioIndexRegisters(); + void calcCriFrameNo(); + void calcCompoundFrameNo(); + void calcTotalFocusTypeNumber(); + void calcTxRxParameters(); + + QVector calcDtgcLut(QList dtgcSlider, float dtgcLen, float maxWeight); + +protected: + quint8 _compoundModeNumber; + + virtual void initRegisterSpace() = 0; + virtual void calcFrameParameters() = 0; + virtual void calcPulseIntervalFrameRate() = 0; + virtual void calcPulseProperties() = 0; + virtual void calcRxBeamFormerProperties() = 0; + virtual void calcReceiverConfigProperties() = 0; + virtual void calcFreqLut() = 0; + virtual void calcIndexParameters() = 0; + +public: + ScenGenUserParameters_t userParams; + ScenGenSystemParameters_t sysParams; + ScenGenProbeParameters_t probeParams; + + ScenGenSoftwareOutput_t softwareOutput; + ScenGenHardwareOutput_t hardwareOuput; + + QList frameParams; + + quint8 compoundFrameNumber; + + void calcScanConversionParameters(); + void calcDtgcLut(); + + BaseScenario(ScenGenUserParameters_t userParams, + ScenGenSystemParameters_t sysParams, + ScenGenProbeParameters_t probeParams); + + virtual ~BaseScenario() + { + } + + void calcSecondaryProbeParameters(); + + void generate(); +}; + +#endif //BASESCENARIO_H diff --git a/include/model/scenarioGenerator/core/scenario/Bm/BmModeScenario.h b/include/model/scenarioGenerator/core/scenario/Bm/BmModeScenario.h new file mode 100644 index 0000000..50881fe --- /dev/null +++ b/include/model/scenarioGenerator/core/scenario/Bm/BmModeScenario.h @@ -0,0 +1,37 @@ +#ifndef BMMODESCENARIO_H +#define BMMODESCENARIO_H + +#include "model/scenarioGenerator/core/scenario/BaseScenario.h" + +class BmModeScenario : public BaseScenario +{ +private: + +protected: + void initRegisterSpace() override; + void calcFrameParameters() override; + void calcPulseIntervalFrameRate() override; + void calcIndexParameters() override; + void calcPulseProperties() override; + void calcRxBeamFormerProperties() override; + void calcReceiverConfigProperties() override; + void calcFreqLut() override; + +public: + float mLinesPri; + quint32 bmRatio; + quint32 mLineNumber; + float b2mPulseInterval; + quint32 mTxShotNumber; + quint32 bRemPulseNumber; + + BmModeScenario(ScenGenUserParameters_t userParam, + ScenGenSystemParameters_t sysParam, + ScenGenProbeParameters_t probeParam); + + ~BmModeScenario() override + { + } +}; + +#endif //BMMODESCENARIO_H diff --git a/include/model/scenarioGenerator/core/scenario/type/frame/BFrame.h b/include/model/scenarioGenerator/core/scenario/type/frame/BFrame.h new file mode 100644 index 0000000..7472479 --- /dev/null +++ b/include/model/scenarioGenerator/core/scenario/type/frame/BFrame.h @@ -0,0 +1,28 @@ +#ifndef BFRAME_H +#define BFRAME_H + +#include "model/scenarioGenerator/core/scenario/type/frame/BaseFrame.h" + +class BFrame : public BaseFrame +{ +private: + +protected: + void setFocusAx() override; + void setScan() override; + void setMlaStb() override; + void setSteering(quint32 frameIndex) override; + void setFrequency() override; + void setLineDensity() override; + void setShotPerLine() override; + void setPriExtension() override; + +public: + BFrame(ScenGenUserParameters_t userParams, + ScenGenSystemParameters_t sysParams, + ScenGenProbeParameters_t probeParams); + + ~BFrame() override; +}; + +#endif //BFRAME_H diff --git a/include/model/scenarioGenerator/core/scenario/type/frame/BaseFrame.h b/include/model/scenarioGenerator/core/scenario/type/frame/BaseFrame.h new file mode 100644 index 0000000..0ff2af7 --- /dev/null +++ b/include/model/scenarioGenerator/core/scenario/type/frame/BaseFrame.h @@ -0,0 +1,100 @@ +#ifndef BASEFRAME_H +#define BASEFRAME_H + +#include + +#include "model/scenarioGenerator/dtoInternal/UserParameters.h" +#include "model/scenarioGenerator/dtoInternal/SystemParameters.h" +#include "model/scenarioGenerator/dtoInternal/ProbeParameters.h" +#include "model/scenarioGenerator/core/scenario/type/misc/Aperture.h" +#include "model/scenarioGenerator/core/scenario/type/misc/Delay.h" +#include "model/scenarioGenerator/core/scenario/type/misc/Point.h" + +class BaseFrame +{ +public: + void setC0dRdAx(); + void setShotLineNumber(); + void setRxFocusPointNumber(); + void setFocusR(); + void setPulseInterval(); + void setOtherParameters(); + void setInterceptFocus(); + void setAperture(); + void setMinMaxDelay(); + void setInterceptPointFiringTime(); + void setRxActiveElementStep(); + void repeatMultiFocus(); + void repeatRxInterceptR0(); + + QVector rxApertureSize(QVector fNumber, QList points); + +protected: + ScenGenUserParameters_t _userParams; + ScenGenSystemParameters_t _sysParams; + ScenGenProbeParameters_t _probeParams; + + virtual void setScan() = 0; + virtual void setShotPerLine() = 0; + virtual void setMlaStb() = 0; + virtual void setLineDensity() = 0; + virtual void setPriExtension() = 0; + virtual void setFocusAx() = 0; + virtual void setFrequency() = 0; + +public: + float c0; + float dR; + float rxPointDax; + quint32 mla; + quint32 stb; + quint32 focusNumber; + float steering; + float minScanAz; + float maxScanAz; + float minScanAx; + float maxScanAx; + float rangeAx; + float rangeAz; + float pulseInterval; + quint32 rxFocusPointNumber; + quint32 txLineNumber; + quint32 rxLineNumber; + quint32 txShotNumber; + float rxLineDaz; + quint32 rxStbLineNumber; + quint32 focusTypeNumber; + quint32 rxBeamFormerNumber; + QVector interceptAz; + QVector focusR; + QVector r0Az; + QVector txF0; + QVector halfPeriod; + QVector rxF0; + QList txInterceptPoint; + QList focusPoint; + QList rxInterceptPoint; + QList r0Point; + Aperture_t txAperture; + Aperture_t rxAperture; + Delay_t delay; + QVector interceptPointFiringTime; + QVector rxActiveElementStep; + float lineDensity; + quint32 shotPerLine; + float priExtension; + QVector focusAx; + bool ffc; + QVector f0; + + BaseFrame(ScenGenUserParameters_t userParams, + ScenGenSystemParameters_t sysParams, + ScenGenProbeParameters_t probeParams); + + virtual ~BaseFrame(); + + void setParameters(quint32 frameIndex); + virtual void setSteering(quint32 frameIndex) = 0; +}; + +#endif //BASEFRAME_H diff --git a/include/model/scenarioGenerator/core/scenario/type/frame/MFrame.h b/include/model/scenarioGenerator/core/scenario/type/frame/MFrame.h new file mode 100644 index 0000000..6450486 --- /dev/null +++ b/include/model/scenarioGenerator/core/scenario/type/frame/MFrame.h @@ -0,0 +1,28 @@ +#ifndef MFRAME_H +#define MFRAME_H + +#include "model/scenarioGenerator/core/scenario/type/frame/BaseFrame.h" + +class MFrame : public BaseFrame +{ +private: + +protected: + void setFocusAx() override; + void setScan() override; + void setMlaStb() override; + void setSteering(quint32 frameIndex) override; + void setFrequency() override; + void setLineDensity() override; + void setShotPerLine() override; + void setPriExtension() override; + +public: + MFrame(ScenGenUserParameters_t userParams, + ScenGenSystemParameters_t sysParams, + ScenGenProbeParameters_t probeParams); + + ~MFrame() override; +}; + +#endif //MFRAME_H diff --git a/include/model/scenarioGenerator/core/scenario/type/misc/Aperture.h b/include/model/scenarioGenerator/core/scenario/type/misc/Aperture.h new file mode 100644 index 0000000..d06f194 --- /dev/null +++ b/include/model/scenarioGenerator/core/scenario/type/misc/Aperture.h @@ -0,0 +1,12 @@ +#ifndef APERTURE_H +#define APERTURE_H + +#include + +struct Aperture_t { + QVector activeElementNumber; + QVector startActiveElementNumber; + QVector centerActiveElementNumber; +}; + +#endif //APERTURE_H diff --git a/include/model/scenarioGenerator/core/scenario/type/misc/Delay.h b/include/model/scenarioGenerator/core/scenario/type/misc/Delay.h new file mode 100644 index 0000000..8b80740 --- /dev/null +++ b/include/model/scenarioGenerator/core/scenario/type/misc/Delay.h @@ -0,0 +1,18 @@ +#ifndef DELAY_H +#define DELAY_H + +#include + +struct Delay_t { + QVector minDelay; + QVector maxDelay; + QVector maxDelayQ; + QVector rxR0MaxDelay; + QVector rxR0MaxDelayQ; + QVector rxR0MinDelay; + QVector rxR0MinDelayQ; + QVector txR0MinDelay; + QVector txR0MinDelayQ; +}; + +#endif //DELAY_H diff --git a/include/model/scenarioGenerator/core/scenario/type/misc/Point.h b/include/model/scenarioGenerator/core/scenario/type/misc/Point.h new file mode 100644 index 0000000..583681e --- /dev/null +++ b/include/model/scenarioGenerator/core/scenario/type/misc/Point.h @@ -0,0 +1,17 @@ +#ifndef POINT_H +#define POINT_H + +#include + +typedef struct Point_t { + float x; + float y; + float z; + float r; + float theta; + float phi; + float azimuth; + float elevation; +}Point_t; + +#endif //POINT_H diff --git a/include/model/scenarioGenerator/core/scenario/type/misc/Pulse.h b/include/model/scenarioGenerator/core/scenario/type/misc/Pulse.h new file mode 100644 index 0000000..a55fba7 --- /dev/null +++ b/include/model/scenarioGenerator/core/scenario/type/misc/Pulse.h @@ -0,0 +1,14 @@ +#ifndef PULSE_H +#define PULSE_H + +#include + +typedef struct Pulse_t { + quint32 halfPeriod; + quint32 halfCycleNo; + bool pulseVoltSel; + bool startPhase; + quint32 dampingPulseWidth; +}Pulse_t; + +#endif //PULSE_H diff --git a/include/model/scenarioGenerator/core/scenario/type/misc/ReceiverConfig.h b/include/model/scenarioGenerator/core/scenario/type/misc/ReceiverConfig.h new file mode 100644 index 0000000..b6c6ac4 --- /dev/null +++ b/include/model/scenarioGenerator/core/scenario/type/misc/ReceiverConfig.h @@ -0,0 +1,24 @@ +#ifndef RECEIVERCONFIG_H +#define RECEIVERCONFIG_H + +#include + +struct ReceiverConfig_t { + quint32 mla; + quint32 lineMode; + quint32 aTgcSel; + quint32 stbEn; + quint32 stb; + quint32 subtractFilterEn; + quint32 dcCancelEn; + quint32 ncoFreqSel; + quint32 lpfSel; + quint32 absEn; + quint32 focusNo; + quint32 lineFilterEn; + quint32 ddcEn; + quint32 wmfEn; + quint32 dpeEn; +}; + +#endif //RECEIVERCONFIG_H diff --git a/include/model/scenarioGenerator/core/scenario/type/misc/RxBeamFormer.h b/include/model/scenarioGenerator/core/scenario/type/misc/RxBeamFormer.h new file mode 100644 index 0000000..c5fd7cc --- /dev/null +++ b/include/model/scenarioGenerator/core/scenario/type/misc/RxBeamFormer.h @@ -0,0 +1,11 @@ +#ifndef RXBEAMFORMER_H +#define RXBEAMFORMER_H +#include + +struct RxBeamFormer_t { + quint32 mla; + quint32 lag; + quint32 apodizationSel; +}; + +#endif //RXBEAMFORMER_H diff --git a/include/model/scenarioGenerator/dto/computational/ScenGenZoomGate.h b/include/model/scenarioGenerator/dto/computational/ScenGenZoomGate.h new file mode 100644 index 0000000..0c96068 --- /dev/null +++ b/include/model/scenarioGenerator/dto/computational/ScenGenZoomGate.h @@ -0,0 +1,18 @@ +#ifndef SCENGENZOOMGATE_H +#define SCENGENZOOMGATE_H + +#include + +typedef struct ScenGenZoomGate_t +{ + float startAzimuth; //x + float endAzimuth; //x + float startAxial; //z + float endAxial; //z + bool linear; + bool VirtualConvex; +}ScenGenZoomGate_t; + +Q_DECLARE_METATYPE(ScenGenZoomGate_t) + +#endif //SCENGENZOOMGATE_H diff --git a/include/model/scenarioGenerator/dto/hardware/HardwareOutput.h b/include/model/scenarioGenerator/dto/hardware/HardwareOutput.h new file mode 100644 index 0000000..124a610 --- /dev/null +++ b/include/model/scenarioGenerator/dto/hardware/HardwareOutput.h @@ -0,0 +1,23 @@ +#ifndef HARDWAREOUTPUT_H +#define HARDWAREOUTPUT_H + +#include + +#include "model/scenarioGenerator/dto/hardware/HwScenarioDependent.h" +#include "model/scenarioGenerator/dto/hardware/SramIndex.h" +#include "model/scenarioGenerator/dto/hardware/SramRx.h" +#include "model/scenarioGenerator/dto/hardware/SramTx.h" + +struct ScenGenHardwareOutput_t { + quint32 focusTypeNumber; + quint32 totalTxShotNumber; + QVector rxBeamFormerNumber; + QVector pulseInterval; + + HwRegister_t hwRegister; + SramIndex_t indexParams; + SramRx_t rxParams; + SramTx_t txParams; +}; + +#endif //HARDWAREOUTPUT_H diff --git a/include/model/scenarioGenerator/dto/hardware/HwScenarioDependent.h b/include/model/scenarioGenerator/dto/hardware/HwScenarioDependent.h new file mode 100644 index 0000000..cd030f7 --- /dev/null +++ b/include/model/scenarioGenerator/dto/hardware/HwScenarioDependent.h @@ -0,0 +1,29 @@ +#ifndef HWSCENARIODEPENDENT_H +#define HWSCENARIODEPENDENT_H + +#include +#include "model/scenarioGenerator/core/scenario/type/misc/Pulse.h" +#include "model/scenarioGenerator/core/scenario/type/misc/RxBeamFormer.h" +#include "model/scenarioGenerator/core/scenario/type/misc/ReceiverConfig.h" + +struct HwRegister_t { + QVector dtgcLut; + QVector > blendWeight; + QVector elementXPosition; + QVector elementYPosition; + QVector elementZPosition; + QVector freqLut; + quint32 scenarioStartIndex; + quint32 scenarioEndIndex; + QList pulseProps; + quint8 pulseTypeNumber; + quint8 rxBeamFormerTypeNumber; + QList rxBeamFormerProps; + quint8 receiverConfigTypeNumber; + QList receiverConfigProps; + QList> lpfLut; + QList> atgcLut; + QList> apodizationLut; +}; + +#endif //HWSCENARIODEPENDENT_H diff --git a/include/model/scenarioGenerator/dto/hardware/SramIndex.h b/include/model/scenarioGenerator/dto/hardware/SramIndex.h new file mode 100644 index 0000000..d6ef17c --- /dev/null +++ b/include/model/scenarioGenerator/dto/hardware/SramIndex.h @@ -0,0 +1,17 @@ +#ifndef SRAMINDEX_H +#define SRAMINDEX_H + +#include + +struct SramIndex_t { + QVector shotPropertiesIndex; + QVector pulsePropertiesIndex; + QVector receiverConfigurationIndex; + QVector firstLineInFrame; + QVector lastLineInFrame; + QVector dLineNum; + QVector dEnsembleNum; + quint8 frameType; +}; + +#endif //SRAMINDEX_H diff --git a/include/model/scenarioGenerator/dto/hardware/SramRx.h b/include/model/scenarioGenerator/dto/hardware/SramRx.h new file mode 100644 index 0000000..0872ef6 --- /dev/null +++ b/include/model/scenarioGenerator/dto/hardware/SramRx.h @@ -0,0 +1,59 @@ +#ifndef SRAMRX_H +#define SRAMRX_H + +#include + +struct SramRx_t { + QVector rxR0CenterActiveElementNumber; + QVector rxR0ActiveElementNumber; + QVector rxActiveElementStep; + QVector interceptPointFiringTime; + QVector r0Position; + QVector rxFocusPointNumber; + QVector thetaCos; + QVector thetaSin; + QVector phiCos; + QVector phiSin; + QVector interceptXPos; + QVector interceptYPos; + QVector interceptZPos; + QVector txR0MinDelay; + QVector rxR0MinDelay; + QVector rxR0MaxDelay; + QVector txR0MinDelayQ; + QVector rxR0MinDelayQ; + QVector rxR0MaxDelayQ; + QVector rxR0StartActiveElementNumber; + QVector r0XPosition; + QVector r0YPosition; + QVector r0ZPosition; + + void clear() + { + rxR0CenterActiveElementNumber.clear(); + rxR0ActiveElementNumber.clear(); + rxActiveElementStep.clear(); + interceptPointFiringTime.clear(); + r0Position.clear(); + rxFocusPointNumber.clear(); + thetaCos.clear(); + thetaSin.clear(); + phiCos.clear(); + phiSin.clear(); + interceptXPos.clear(); + interceptYPos.clear(); + interceptZPos.clear(); + txR0MinDelay.clear(); + rxR0MinDelay.clear(); + rxR0MaxDelay.clear(); + txR0MinDelayQ.clear(); + rxR0MinDelayQ.clear(); + rxR0MaxDelayQ.clear(); + rxR0StartActiveElementNumber.clear(); + r0XPosition.clear(); + r0YPosition.clear(); + r0ZPosition.clear(); + } +}; + +#endif //SRAMRX_H diff --git a/include/model/scenarioGenerator/dto/hardware/SramTx.h b/include/model/scenarioGenerator/dto/hardware/SramTx.h new file mode 100644 index 0000000..6d7ffce --- /dev/null +++ b/include/model/scenarioGenerator/dto/hardware/SramTx.h @@ -0,0 +1,35 @@ +#ifndef SRAMTX_H +#define SRAMTX_H + +#include + +struct SramTx_t { + QVector txFocusXPos; + QVector txFocusYPos; + QVector txFocusZPos; + QVector txStartActiveElementNumber; + QVector txActiveElementNumber; + QVector minDelay; + QVector maxDelay; + QVector maxDelayQ; + QVector interceptXPos; + QVector interceptYPos; + QVector interceptZPos; + + void clear() + { + txFocusXPos.clear(); + txFocusYPos.clear(); + txFocusZPos.clear(); + txStartActiveElementNumber.clear(); + txActiveElementNumber.clear(); + minDelay.clear(); + maxDelay.clear(); + maxDelayQ.clear(); + interceptXPos.clear(); + interceptYPos.clear(); + interceptZPos.clear(); + } +}; + +#endif //SRAMTX_H diff --git a/include/model/scenarioGenerator/dto/software/Pixel.h b/include/model/scenarioGenerator/dto/software/Pixel.h new file mode 100644 index 0000000..ee4ff5f --- /dev/null +++ b/include/model/scenarioGenerator/dto/software/Pixel.h @@ -0,0 +1,15 @@ +#ifndef PIXEL_H +#define PIXEL_H + +#include + +struct Pixel_t { + float minPixelXPos; + float minPixelZPos; + float pixelXStep; + float pixelZStep; + quint32 pixelXNo; + quint32 pixelZNo; +}; + +#endif //PIXEL_H diff --git a/include/model/scenarioGenerator/dto/software/ScanConversionConfig.h b/include/model/scenarioGenerator/dto/software/ScanConversionConfig.h new file mode 100644 index 0000000..11e5f09 --- /dev/null +++ b/include/model/scenarioGenerator/dto/software/ScanConversionConfig.h @@ -0,0 +1,148 @@ +#ifndef SCANCONVERSIONCONFIG_H +#define SCANCONVERSIONCONFIG_H + +#include + +#include "math.h" + +#include "model/scenarioGenerator/dto/software/Pixel.h" + +struct ScenGenScanConversionConfig_t +{ +private: + float frameMaxXScan; + float frameMinXScan; + float frameMaxZScan; + float frameMinZScan; + + void calcPixelParamConvex() + { + frameMaxXScan = probeRadius * sinf(bMaxScanAz) + bMaxScanAx * sinf( + bMaxScanAz / fieldOfView * angle); + + frameMinXScan = probeRadius * sinf(bMinScanAz) + bMaxScanAx * sinf( + bMinScanAz / fieldOfView * angle); + + auto maxAbsScanAz = qMax(abs(bMinScanAz), abs(bMaxScanAz)); + float minAbsScanAz; + + if(bMaxScanAz > 0 && bMinScanAz < 0) + { + minAbsScanAz = 0; + } + else + { + minAbsScanAz = qMin(abs(bMinScanAz), abs(bMaxScanAz)); + } + + frameMaxZScan = probeRadius * cosf(minAbsScanAz) + bMaxScanAx * cosf( + minAbsScanAz / fieldOfView * angle); + + frameMinZScan = probeRadius * cosf(maxAbsScanAz) + bMinScanAx * cosf( + maxAbsScanAz / fieldOfView * angle); + } + + void calcPixelParamVirtualConvex() + { + float minAbsScanAz; + if(bMaxScanAz > 0 && bMinScanAz < 0) + { + minAbsScanAz = 0; + } + else + { + minAbsScanAz = qMin(abs(bMinScanAz), abs(bMaxScanAz)); + } + + auto maxAbsScanAz = qMax(abs(bMinScanAz), abs(bMaxScanAz)); + frameMaxZScan = bMaxScanAx * cos(minAbsScanAz / fieldOfView * 2 * vcMaxTheta); + + frameMinZScan = bMinScanAx * cos(maxAbsScanAz / fieldOfView * 2 * vcMaxTheta); + + frameMaxXScan = virtualOriginalZ * tanf(bMaxScanAz) + bMaxScanAx * sinf( + bMaxScanAz / fieldOfView * 2 * vcMaxTheta); + + frameMinXScan = virtualOriginalZ * tanf(bMinScanAz) + bMaxScanAx * sinf( + bMinScanAz / fieldOfView * 2 * vcMaxTheta); + } + + void calcPixelParamLinear() + { + frameMaxXScan = bMaxScanAz; + frameMinXScan = bMinScanAz; + frameMaxZScan = bMaxScanAx; + frameMinZScan = bMinScanAx; + } + + void calculateMeshGrid(quint32 xPixelnumber, quint32 zPixelNumber, bool hdZoom) + { + auto pixelXStep = (frameMaxXScan - frameMinXScan) / (xPixelnumber - 1); + auto pixelZStep = (frameMaxZScan - frameMinZScan) / (zPixelNumber - 1); + + float pixelStep; + + pixelStep = pixelZStep; + + auto finalPixelXNo = qMin(floor((frameMaxXScan - frameMinXScan) / pixelStep) + 1, + xPixelnumber); + auto finalPixelZNo = qMin(floor((frameMaxZScan - frameMinZScan) / pixelStep) + 1, + zPixelNumber); + + pixel.minPixelXPos = (frameMinXScan + frameMaxXScan) / 2.0f - pixelStep * + (finalPixelXNo - 1) / + 2.0f; + pixel.minPixelZPos = (frameMinZScan + frameMaxZScan) / 2.0f - pixelStep * + (finalPixelZNo - 1) / + 2.0f; + pixel.pixelXStep = pixelStep; + pixel.pixelZStep = pixelStep; + pixel.pixelXNo = finalPixelXNo; + pixel.pixelZNo = finalPixelZNo; + } + +public: + bool linear; + float probeRadius; + float fieldOfView; + float probeFieldOfView; + float virtualOriginalZ; + float bMinScanAx; + float bMinScanAz; + float bMaxScanAx; + float bMaxScanAz; + float minScanAx; + float minScanAz; + float maxScanAx; + float steering; + quint32 rxLineNo; + quint32 rxFocusPointNo; + float rxLineDaz; + float rxPointDax; + bool virtualConvex; + float vcMaxTheta; + float angle; + Pixel_t pixel; + + void calcPixelParams(quint32 xPixelnumber, quint32 zPixelNumber, bool hdZoom) + { + if(linear) + { + if(virtualConvex) + { + calcPixelParamVirtualConvex(); + } + else + { + calcPixelParamLinear(); + } + } + else + { + calcPixelParamConvex(); + } + + calculateMeshGrid(xPixelnumber, zPixelNumber, hdZoom); + } +}; + +#endif //SCANCONVERSIONCONFIG_H diff --git a/include/model/scenarioGenerator/dto/software/SoftwareOutput.h b/include/model/scenarioGenerator/dto/software/SoftwareOutput.h new file mode 100644 index 0000000..37a822c --- /dev/null +++ b/include/model/scenarioGenerator/dto/software/SoftwareOutput.h @@ -0,0 +1,34 @@ +#ifndef SWOUTPUT_H +#define SWOUTPUT_H + +#include + +#include "model/scenarioGenerator/dto/software/SwScenarioDependent.h" +#include "model/scenarioGenerator/dto/software/ScanConversionConfig.h" + +struct ScenGenSoftwareOutput_t +{ + quint32 outputWidth; + quint32 outputHeight; + + quint8 rejectB; + quint8 sri; + quint8 enhanceB; + quint8 dynamicContrastBSelector; + qint8 gainB; + quint8 tintMapBSelector; + quint8 tintMapMSelector; + quint8 cri; + quint8 criFilterMode; + quint8 persist; + quint8 frameFilterMode; + QList grayMapB; + QList grayMapM; + + SwScenarioDependent_t scenarioDependent; + QList scanConversionProps; +}; + +Q_DECLARE_METATYPE(ScenGenSoftwareOutput_t) + +#endif //SWOUTPUT_H diff --git a/include/model/scenarioGenerator/dto/software/SwScenarioDependent.h b/include/model/scenarioGenerator/dto/software/SwScenarioDependent.h new file mode 100644 index 0000000..b9dca1a --- /dev/null +++ b/include/model/scenarioGenerator/dto/software/SwScenarioDependent.h @@ -0,0 +1,11 @@ +#ifndef SWSCENARIODEPENDENT_H +#define SWSCENARIODEPENDENT_H + +#include + +struct SwScenarioDependent_t { + quint8 criFrameNumber; + float frameRate; +}; + +#endif //SWSCENARIODEPENDENT_H diff --git a/include/model/scenarioGenerator/dtoInternal/ProbeParameters.h b/include/model/scenarioGenerator/dtoInternal/ProbeParameters.h new file mode 100644 index 0000000..c55df5d --- /dev/null +++ b/include/model/scenarioGenerator/dtoInternal/ProbeParameters.h @@ -0,0 +1,120 @@ +#ifndef PROBEPARAMETERS_H +#define PROBEPARAMETERS_H + +#include + +#include "model/scenarioGenerator/dtoInternal/probe/ProbeProperties.h" +#include "model/scenarioGenerator/dtoInternal/probe/SecondaryProbeProperties.h" + +struct ScenGenProbeParameters_t { +private: + ScenGenProbeProperties_t _probeProps; + ScenGenSecondaryProbeProperties_t _scndProbeProps; + + void calcConvexScndProps(float dr, float angle) + { + _scndProbeProps.pitchAzimuth = 2 * asinf(_probeProps.pitch / 2 / _probeProps.radius); + + _scndProbeProps.correctionZ = -_probeProps.radius * + cosf( + (_probeProps.elementNo - 1) / 2.0f * _scndProbeProps.pitchAzimuth) / dr; + + for(auto i = 0; i < _probeProps.elementNo; i++) + { + auto temp = ((1 - _probeProps.elementNo) / 2.0f + i) * _scndProbeProps.pitchAzimuth; + _scndProbeProps.elementAzimuth.push_back(temp); + + _scndProbeProps.elementXPosition.push_back(_probeProps.radius * sinf(temp) / dr); + + _scndProbeProps.elementYPosition.push_back(0); + + _scndProbeProps.elementZPosition.push_back(_probeProps.radius * cosf( + temp) / dr + + _scndProbeProps.correctionZ); + } + + _scndProbeProps.vcMaxTheta = 0; + + if(angle < _probeProps.fieldOfView) + { + _scndProbeProps.fieldOfView = angle; + _scndProbeProps.virtualOriginalZ = 0; + } + else + { + _scndProbeProps.fieldOfView = _probeProps.fieldOfView; + _scndProbeProps.virtualOriginalZ = _probeProps.radius * + (cosf(_scndProbeProps.fieldOfView / 2) - + sinf(_scndProbeProps.fieldOfView / 2) / + tanf(angle / 2)); + } + } + + void calcLinearScndProps(float dr, bool virtualConvex) + { + _scndProbeProps.pitchAzimuth = _probeProps.pitch; + + _scndProbeProps.correctionZ = 0; + + for(auto i = 0; i < _probeProps.elementNo; i++) + { + _scndProbeProps.elementAzimuth.push_back( + ((1 - _probeProps.elementNo) / 2.0f + i) * _scndProbeProps.pitchAzimuth); + + _scndProbeProps.elementXPosition.push_back(_scndProbeProps.elementAzimuth[i] / dr); + + _scndProbeProps.elementYPosition.push_back(0); + + _scndProbeProps.elementZPosition.push_back(0); + } + + if(virtualConvex) + { + _scndProbeProps.vcMaxTheta = _probeProps.vcMaxTheta; + _scndProbeProps.virtualOriginalZ = _probeProps.fieldOfView / 2 / tanf( + _scndProbeProps.vcMaxTheta); + _scndProbeProps.fieldOfView = 2 * _scndProbeProps.vcMaxTheta; + } + else + { + _scndProbeProps.vcMaxTheta = 0; + _scndProbeProps.virtualOriginalZ = 0; + _scndProbeProps.fieldOfView = _probeProps.fieldOfView; + } + } + +public: + ScenGenProbeProperties_t getProbeProps() + { + return _probeProps; + } + + ScenGenSecondaryProbeProperties_t getScndProbeProps() + { + return _scndProbeProps; + } + + void setProbeProps(ScenGenProbeProperties_t probeProps) + { + _probeProps = probeProps; + } + + void setScndProbeProps(ScenGenSecondaryProbeProperties_t probeProps) + { + _scndProbeProps = probeProps; + } + + void calcScndProps(float dr, float angle, bool virtualConvex) + { + if(_probeProps.linear) + { + calcLinearScndProps(dr, virtualConvex); + } + else + { + calcConvexScndProps(dr, angle); + } + } +}; + +#endif //PROBEPARAMETERS_H diff --git a/include/model/scenarioGenerator/dtoInternal/ScenGenDatabase.h b/include/model/scenarioGenerator/dtoInternal/ScenGenDatabase.h new file mode 100644 index 0000000..6a9c736 --- /dev/null +++ b/include/model/scenarioGenerator/dtoInternal/ScenGenDatabase.h @@ -0,0 +1,19 @@ +#ifndef SCENGENDATABASE_H +#define SCENGENDATABASE_H + +#include + +struct ScenGenDatabase_t { + QList > lineFilterLut; + QVector apodization1; + QVector apodization2; + QVector apodization3; + QVector apodization4; + QList lpf; + QVector atgcB; + QVector atgcD; + QVector atgcPw; + QVector atgcReserve; +}; + +#endif //SCENGENDATABASE_H diff --git a/include/model/scenarioGenerator/dtoInternal/SystemParameters.h b/include/model/scenarioGenerator/dtoInternal/SystemParameters.h new file mode 100644 index 0000000..92fbe69 --- /dev/null +++ b/include/model/scenarioGenerator/dtoInternal/SystemParameters.h @@ -0,0 +1,43 @@ +#ifndef SYSTEMPARAMETERS_H +#define SYSTEMPARAMETERS_H + +#include + +#include "model/databaseManager/dto/System/DbmSysParameters.h" + +struct ScenGenSystemParameters_t { + float dtgcMaxWeight; + QList blendShotWeight; + float delayCalcDt; + float lineDt; + float fpgaTxDt; + quint32 apodization; + float startDepth; + quint32 maxBPulseNumber; + quint32 maxRxFocusPointNumber; + quint32 channelNumber; + quint8 mla; + quint32 stb; + + ScenGenSystemParameters_t() + { + } + + ScenGenSystemParameters_t(DbmDtoSysParameters data) + { + delayCalcDt = static_cast(data.delayCalcDt); + lineDt = static_cast(data.lineDt); + fpgaTxDt = static_cast(data.fpgaTxDt); + apodization = static_cast(data.apodization); + startDepth = static_cast(data.startDepth); + maxBPulseNumber = 256; + maxRxFocusPointNumber = 8192; + channelNumber = 192; + dtgcMaxWeight = 10; + mla = 1; + stb = 0; + blendShotWeight = {1, 1, 1, 1}; + } +}; + +#endif //SYSTEMPARAMETERS_H diff --git a/include/model/scenarioGenerator/dtoInternal/UserParameters.h b/include/model/scenarioGenerator/dtoInternal/UserParameters.h new file mode 100644 index 0000000..9f2e8b4 --- /dev/null +++ b/include/model/scenarioGenerator/dtoInternal/UserParameters.h @@ -0,0 +1,51 @@ +#ifndef USERPARAMETERS_H +#define USERPARAMETERS_H + +#include + +struct ScenGenUserParameters_t { + QList dtgc; + quint8 focusNumber; + bool focusFrequencyCompound; + quint8 focus; + float depth; + float angle; + bool harmonicImaging; + bool virtualConvex; + quint8 oti; + bool pulseInversion; + quint8 frequency; + bool hdZoom; + quint32 X; + quint32 Z; + quint32 lineDensity; + quint8 lineFilter; + bool bMQuality; + float minScanAx; + float maxScanAx; + float minScanAz; + float maxScanAz; + quint8 aoB; + + quint8 rejectB; + quint8 rejectM; + quint8 sri; + quint8 cri; + quint8 criFilter; + quint8 enhanceB; + quint8 enhanceM; + quint8 dynamicContrastBSelector; + quint8 dynamicContrastMSelector; + qint8 gainB; + qint8 gainM; + quint8 tintMapBSelector; + quint8 tintMapMSelector; + quint8 persist; + quint8 frameFilterMode; + QList grayMapB; + QList grayMapM; + quint8 speed; + float mLineAzimuth; +}; + +#endif //USERPARAMETERS_H diff --git a/include/model/scenarioGenerator/dtoInternal/probe/ProbeProperties.h b/include/model/scenarioGenerator/dtoInternal/probe/ProbeProperties.h new file mode 100644 index 0000000..6551c3f --- /dev/null +++ b/include/model/scenarioGenerator/dtoInternal/probe/ProbeProperties.h @@ -0,0 +1,111 @@ +#ifndef PROBEPROPERTIES_H +#define PROBEPROPERTIES_H + +#include +#include + +#include "model/ssm/dtoInternal/SsmProbeProperties.h" + +typedef struct ScenGenProbeProperties_t { + bool linear; + float pitch; + float radius; + int subAzimuthNo; + int subElevationNo; + int elementNo; + float elementWidth; + float elementHeight; + float fieldOfView; + QVector impulseResponse; + QList angleValues; + QList focusValues; + QList hiFocusValues; + int multiFocusStep; + QList otiC0Values; + QList > ffcValues; + QList depthData; + QList frequencyValues; + QList hiFrequencyValues; + QList dFrequencyValues; + QList pwFrequencyValues; + QList > criSteeringAngles; + float rxGain; + float txGain; + QList lineDensityValues; + QList dLineDensityValues; + int halfCycleNoValues; + int ffcHalfCycleNoValues; + QList hiHalfCycleNoValues; + QList dopplerHalfCycleNoValues; + QList priExtensionValue; + float dPriExtensionValue; + float txResolution; + float rxResolution; + float mLinesPri; + int simultPwFrameRate; + QVector virtualConvexLineDensityValues; + float vcMaxTheta; + QList piValues; + QList hiNames; + QList AtgcB; + QList AtgcD; + QList AtgcPW; + QList AtgcReserve; + + ScenGenProbeProperties_t() + { + } + + ScenGenProbeProperties_t(SsmProbeProperties_t temp) + { + linear = temp.linear; + pitch = temp.pitch; + radius = temp.radius; + subAzimuthNo = temp.subAzimuthNo; + subElevationNo = temp.subElevationNo; + elementNo = temp.elementNo; + elementWidth = temp.elementWidth; + elementHeight = temp.elementHeight; + fieldOfView = temp.fieldOfView; + impulseResponse = QVector::fromList(temp.impulseResponse); + angleValues = temp.angleValues; + focusValues = temp.focusValues; + hiFocusValues = temp.hiFocusValues; + multiFocusStep = temp.multiFocusStep; + otiC0Values = temp.otiC0Values; + ffcValues = temp.ffcValues; + depthData = temp.depthData; + frequencyValues = temp.frequencyValues; + hiFrequencyValues = temp.hiFrequencyValues; + dFrequencyValues = temp.dFrequencyValues; + pwFrequencyValues = temp.pwFrequencyValues; + criSteeringAngles = temp.criSteeringAngles; + rxGain = temp.rxGain; + txGain = temp.txGain; + lineDensityValues = temp.lineDensityValues; + dLineDensityValues = temp.dLineDensityValues; + halfCycleNoValues = temp.halfCycleNoValues; + ffcHalfCycleNoValues = temp.ffcHalfCycleNoValues; + hiHalfCycleNoValues = temp.hiHalfCycleNoValues; + dopplerHalfCycleNoValues = temp.dopplerHalfCycleNoValues; + priExtensionValue = temp.priExtensionValue; + dPriExtensionValue = temp.dPriExtensionValue; + txResolution = temp.txResolution; + rxResolution = temp.rxResolution; + mLinesPri = temp.mLinesPri; + simultPwFrameRate = temp.simultPwFrameRate; + virtualConvexLineDensityValues = QVector::fromList( + temp.virtualConvexLineDensityValues); + vcMaxTheta = temp.vcMaxTheta; + piValues = temp.piValues; + hiNames = temp.hiNames; + AtgcB = temp.AtgcB; + AtgcD = temp.AtgcD; + AtgcPW = temp.AtgcPW; + AtgcReserve = temp.AtgcReserve; + } +}ScenGenProbeProperties_t; + +Q_DECLARE_METATYPE(ScenGenProbeProperties_t) + +#endif //PROBEPROPERTIES_H diff --git a/include/model/scenarioGenerator/dtoInternal/probe/SecondaryProbeProperties.h b/include/model/scenarioGenerator/dtoInternal/probe/SecondaryProbeProperties.h new file mode 100644 index 0000000..bcd0a48 --- /dev/null +++ b/include/model/scenarioGenerator/dtoInternal/probe/SecondaryProbeProperties.h @@ -0,0 +1,22 @@ +#ifndef PROBESECONDPARAMETERS_H +#define PROBESECONDPARAMETERS_H + +#include +#include + +typedef struct ScenGenSecondaryProbeProperties_t +{ + float pitchAzimuth; + float correctionZ; + QVector elementAzimuth; + QVector elementXPosition; + QVector elementYPosition; + QVector elementZPosition; + float vcMaxTheta; + float virtualOriginalZ; + float fieldOfView; +}ScenGenSecondaryProbeProperties_t; + +Q_DECLARE_METATYPE(ScenGenSecondaryProbeProperties_t); + +#endif //PROBESECONDPARAMETERS_H diff --git a/include/model/scenarioGenerator/utils/H5Macros.h b/include/model/scenarioGenerator/utils/H5Macros.h new file mode 100644 index 0000000..feaaf08 --- /dev/null +++ b/include/model/scenarioGenerator/utils/H5Macros.h @@ -0,0 +1,148 @@ +#ifndef H5MACROS_H +#define H5MACROS_H + +#define WRITE_INTERNAL_VECTOR_DATASET(input, paramsName, listName, nameStr, dataType) \ + do \ + { \ + auto listName ## _data = input.paramsName.listName.data(); \ + hsize_t dims[1]{static_cast(input.paramsName.listName.count())}; \ + H5::DataSpace* dataspace = new H5::DataSpace(1, dims); \ + H5::DataSet* dataset = \ + new H5::DataSet(_file.createDataSet(nameStr, \ + H5::PredType::dataType, *dataspace, H5P_DEFAULT, \ + H5P_DEFAULT, H5P_DEFAULT)); \ + dataset->write(listName ## _data, \ + H5::PredType::dataType, \ + H5P_DEFAULT, \ + H5P_DEFAULT, \ + H5P_DEFAULT); \ + delete dataspace; \ + delete dataset; \ + } \ + while(0) \ + + +//halfPeriodVector.append(input.hwRegister.pulseProps.at(i).halfPeriod) +#define WRITE_INTERNAL_QTZD_VECTOR_DS(input, \ + paramsName, \ + listName, \ + qName, \ + nameStr, \ + dataType) \ + do \ + { \ + auto tempMember = input.paramsName.listName.at(0).qName; \ + QVector list; \ + for(int i = 0; i < input.paramsName.listName.count(); ++i) \ + { \ + list.append(input.paramsName.listName.at(i).qName); \ + } \ + auto listName ## _data = list.data(); \ + hsize_t dims[1]{static_cast(list.count())}; \ + H5::DataSpace* dataspace = new H5::DataSpace(1, dims); \ + H5::DataSet* dataset = \ + new H5::DataSet(_file.createDataSet(nameStr, \ + H5::PredType::dataType, *dataspace, H5P_DEFAULT, \ + H5P_DEFAULT, H5P_DEFAULT)); \ + dataset->write(listName ## _data, \ + H5::PredType::dataType, \ + H5P_DEFAULT, \ + H5P_DEFAULT, \ + H5P_DEFAULT); \ + delete dataspace; \ + delete dataset; \ + } \ + while(0) \ + +#define WRITE_INTERNAL_2D_VECTOR_DATASET(input, paramsName, listName, nameStr, dataType) \ + do \ + { \ + auto tempMember = input.paramsName.listName.at(0).at(0); \ + QVector list; \ + for(int i = 0; i < input.paramsName.listName.count(); ++i){ \ + for(int j = 0; j < input.paramsName.listName.at(i).count(); ++j){ \ + list.append(input.paramsName.listName.at(i).at(j)); \ + } \ + } \ + auto listName ## _data = list.data(); \ + hsize_t dims[1]{static_cast(list.count())}; \ + H5::DataSpace* dataspace = new H5::DataSpace(1, dims); \ + H5::DataSet* dataset = \ + new H5::DataSet(_file.createDataSet(nameStr, \ + H5::PredType::dataType, *dataspace, H5P_DEFAULT, \ + H5P_DEFAULT, H5P_DEFAULT)); \ + dataset->write(listName ## _data, \ + H5::PredType::dataType, \ + H5P_DEFAULT, \ + H5P_DEFAULT, \ + H5P_DEFAULT); \ + delete dataspace; \ + delete dataset; \ + } \ + while(0) \ + + +#define WRITE_VECTOR_DATASET(input, listName, nameStr, dataType) \ + do \ + { \ + auto listName ## _data = input.listName.data(); \ + hsize_t dims[1]{static_cast(input.listName.count())}; \ + H5::DataSpace* dataspace = new H5::DataSpace(1, dims); \ + H5::DataSet* dataset = \ + new H5::DataSet(_file.createDataSet(nameStr, \ + H5::PredType::dataType, *dataspace, H5P_DEFAULT, \ + H5P_DEFAULT, H5P_DEFAULT)); \ + dataset->write(listName ## _data, \ + H5::PredType::dataType, \ + H5P_DEFAULT, \ + H5P_DEFAULT, \ + H5P_DEFAULT); \ + delete dataspace; \ + delete dataset; \ + } \ + while(0) \ + + +#define WRITE_Single_DATASET(input, valueName, nameStr, dataType) \ + do \ + { \ + auto valueName ## _data = &input.valueName; \ + hsize_t dims[1]{static_cast(1)}; \ + H5::DataSpace* dataspace = new H5::DataSpace(1, dims); \ + H5::DataSet* dataset = \ + new H5::DataSet(_file.createDataSet(nameStr, \ + H5::PredType::dataType, *dataspace, H5P_DEFAULT, \ + H5P_DEFAULT, H5P_DEFAULT)); \ + dataset->write(valueName ## _data, \ + H5::PredType::dataType, \ + H5P_DEFAULT, \ + H5P_DEFAULT, \ + H5P_DEFAULT); \ + delete dataspace; \ + delete dataset; \ + } \ + while(0) \ + + +#define WRITE_INTERNAL_SINGLE_DATASET(input, paramsName, valueName, nameStr, dataType) \ + do \ + { \ + auto valueName ## _data = &input.paramsName.valueName; \ + hsize_t dims[1]{static_cast(1)}; \ + H5::DataSpace* dataspace = new H5::DataSpace(1, dims); \ + H5::DataSet* dataset = \ + new H5::DataSet(_file.createDataSet(nameStr, \ + H5::PredType::dataType, *dataspace, H5P_DEFAULT, \ + H5P_DEFAULT, H5P_DEFAULT)); \ + dataset->write(valueName ## _data, \ + H5::PredType::dataType, \ + H5P_DEFAULT, \ + H5P_DEFAULT, \ + H5P_DEFAULT); \ + delete dataspace; \ + delete dataset; \ + } \ + while(0) \ + + +#endif //H5MACROS_H diff --git a/include/model/scenarioGenerator/utils/Macros.h b/include/model/scenarioGenerator/utils/Macros.h new file mode 100644 index 0000000..25c5310 --- /dev/null +++ b/include/model/scenarioGenerator/utils/Macros.h @@ -0,0 +1,38 @@ +#ifndef MACROS_H +#define MACROS_H + +/*************************************************************************************************/ +#define IS_IN_RANGE(val, min, max) \ + (val >= min && val <= max) + +/*************************************************************************************************/ +#define SET_SCENARIO_INDEPENDENT_VALUE(param, val, min, max) \ + if(!IS_IN_RANGE(val, min, max)) \ + { \ + return false; \ + } \ + _input.param = val; \ + calculateScenarioIndependentValues(); \ + return true; + +/*************************************************************************************************/ +#define SET_SCENARIO_DEPENDENT_VALUE(param, val, min, max) \ + if(!IS_IN_RANGE(val, min, max)) \ + { \ + return false; \ + } \ + _input.param = val; \ + calculateScenarioDependentValues(); \ + return true; + +/*************************************************************************************************/ +#define UPDATE_VALUE(TYPE, SETTER) \ + { \ + auto temp = GET_VALUE(request, 0, TYPE); \ + auto result = _core->SETTER(temp); \ + processScenGenCommand(result, request); \ + } + +//#define CHECK_FOR_REGENERATE(TYPE, NAME, ) + +#endif //MACROS_H diff --git a/include/model/ssm/Ssm.h b/include/model/ssm/Ssm.h new file mode 100644 index 0000000..d4d56ce --- /dev/null +++ b/include/model/ssm/Ssm.h @@ -0,0 +1,55 @@ +#ifndef SSM_H +#define SSM_H + +#include "model/ultrasoundModule/UsModule.h" +#include "model/backendImageProcessor/type/EImageMode.h" +#include "model/ssm/dtoInternal/SsmProbeProperties.h" +#include "model/ssm/dtoInternal/SsmPresetValues.h" +#include "model/ssm/dtoInternal/SsmConnectedProbe.h" +#include "model/ssm/dtoInternal/SsmProbeLastConfig.h" + +class Ssm : public UsModule +{ + Q_OBJECT + US_MODULE + SINGLETON(Ssm) + +private: + Ssm(); + ~Ssm() override; + + EImageMode::eImageMode _currentMode; + void updateCurrentMode(const CommandRequest& request); + + SsmProbeProperties_t _probeProps; + SsmPresetValues_t _presetValues; + + QList _connectedProbes; + + bool _forceProbeSelection; + + void getProbeProps(int id); + void sendProbeProps(); + + void getPresetValues(int id); + void sendPresetValues(); + + EImageMode::eImageMode applyFreezeOnCurrentMode(bool freeze); + + EImageMode::eImageMode applyCriOnCurrentMode(bool criEnbleStatus); + QString addCriToMode(QString mode); + + QString addCineToMode(QString mode); + + void startupRoutine(); + void shutdownRoutine(); + void getConnectedProbes(); + void showProbePage(); + void checkForLastProbe(); + + void checkPanel(); + + void saveProbeState(); +}; + +#endif //SSM_H diff --git a/include/model/ssm/Ssm.h.autosave b/include/model/ssm/Ssm.h.autosave new file mode 100644 index 0000000..88de596 --- /dev/null +++ b/include/model/ssm/Ssm.h.autosave @@ -0,0 +1,56 @@ +#ifndef SSM_H +#define SSM_H + +#include "model/ultrasoundModule/UsModule.h" +#include "model/backendImageProcessor/type/EImageMode.h" +#include "model/ssm/dtoInternal/SsmProbeProperties.h" +#include "model/ssm/dtoInternal/SsmPresetValues.h" +#include "model/ssm/dtoInternal/SsmConnectedProbe.h" +#include "model/ssm/dtoInternal/SsmProbeLastConfig.h" + +class Ssm : public UsModule +{ + Q_OBJECT + US_MODULE + SINGLETON(Ssm) + +private: + Ssm(); + ~Ssm() override; + + EImageMode::eImageMode _currentMode; + void updateCurrentMode(const CommandRequest& request); + + SsmProbeProperties_t _probeProps; + SsmPresetValues_t _presetValues; + + QList _connectedProbes; + + bool _forceProbeSelection; + + void getProbeProps(int id); + void sendProbeProps(); + + void getPresetValues(int id); + void sendPresetValues(); + + EImageMode::eImageMode applyFreezeOnCurrentMode(bool freeze); + + EImageMode::eImageMode applyCriOnCurrentMode(bool criEnbleStatus); + QString addCriToMode(QString mode); + + QString addCineToMode(QString mode); + + void selfTest(); + void startupRoutine(); + void shutdownRoutine(); + void getConnectedProbes(); + void showProbePage(); + void checkForLastProbe(); + + bool checkPanel(); + + void saveProbeState(); +}; + +#endif //SSM_H diff --git a/include/model/ssm/dtoInternal/SsmConnectedProbe.h b/include/model/ssm/dtoInternal/SsmConnectedProbe.h new file mode 100644 index 0000000..d074f45 --- /dev/null +++ b/include/model/ssm/dtoInternal/SsmConnectedProbe.h @@ -0,0 +1,15 @@ +#ifndef SSMCONNECTEDPROBE_H +#define SSMCONNECTEDPROBE_H + +#include +#include + +struct SsmConnectedProbe_t +{ + quint32 slot; + quint32 id; +}; + +Q_DECLARE_METATYPE(SsmConnectedProbe_t); + +#endif //SSMCONNECTEDPROBE_H diff --git a/include/model/ssm/dtoInternal/SsmPresetValues.h b/include/model/ssm/dtoInternal/SsmPresetValues.h new file mode 100644 index 0000000..ab560a2 --- /dev/null +++ b/include/model/ssm/dtoInternal/SsmPresetValues.h @@ -0,0 +1,90 @@ +#ifndef SSMPRESETVALUES_H +#define SSMPRESETVALUES_H + +#include +#include + +#include "model/databaseManager/dto/ProbeProperties/DbmPresetValue.h" + +struct SsmPresetValues_t { + int angle; + int apcTxPower; + int criFilter; + int depth; + int dynContB; + int mla; + int stb; + int lineDensity; + float readZoom; + int rejectB; + int framFilter; + int lineFilter; + int criLineFilter; + int cri; + int enhanceB; + int gainB; + int focusNumber; + int persist; + int focus; + int tintMapB; + int grayMapB; + bool sriBypass; + int sri; + int oti; + bool xl; + int frequency; + bool hi; + bool ffc; + bool virtualConvex; + bool criBypass; + bool mirrorLR; + bool mirrorUD; + bool twoDSri; + int imageX; + int imageY; + int tgc; + + void init(DbmDtoPresetValue temp) + { + angle = temp.angle; + apcTxPower = temp.apcTxPower; + criFilter = temp.criFilter; + depth = temp.depth; + dynContB = temp.dynContB; + mla = temp.mla; + stb = temp.stb; + lineDensity = temp.lineDensity; + readZoom = static_cast(temp.readZoom); + rejectB = temp.rejectB; + framFilter = temp.framFilter; + lineFilter = temp.lineFilter; + criLineFilter = temp.criLineFilter; + cri = temp.cri; + enhanceB = temp.enhanceB; + gainB = temp.gainB; + focusNumber = temp.focusNumber; + persist = temp.persist; + focus = temp.focus; + tintMapB = temp.tintMapB; + grayMapB = temp.grayMapB; + sriBypass = temp.sriBypass; + sri = temp.sri; + oti = temp.oti; + xl = temp.xl; + frequency = temp.frequency; + hi = temp.hi; + ffc = temp.ffc; + virtualConvex = temp.virtualConvex; + criBypass = temp.criBypass; + mirrorLR = temp.mirrorLR; + mirrorUD = temp.mirrorUD; + twoDSri = temp.twoDSri; + imageX = temp.imageX; + imageY = temp.imageY; + tgc = temp.tgc; + } +}; + +Q_DECLARE_METATYPE(SsmPresetValues_t); + +#endif //SSMPRESETVALUES_H diff --git a/include/model/ssm/dtoInternal/SsmProbeLastConfig.h b/include/model/ssm/dtoInternal/SsmProbeLastConfig.h new file mode 100644 index 0000000..9392493 --- /dev/null +++ b/include/model/ssm/dtoInternal/SsmProbeLastConfig.h @@ -0,0 +1,26 @@ +#ifndef SSMPROBELASTCONFIG_H +#define SSMPROBELASTCONFIG_H + +#include +#include + +#include "model/databaseManager/dto/ProbeProperties/DbmLastConfig.h" + +struct SsmProbeLastConfig_t +{ + quint32 id; + quint32 slot; + quint32 presetId; + quint32 folderId; + + void init(DbmDtoLastConfig config) + { + id = config.Probe_id; + presetId = config.Preset_id; + folderId = config.Application_id; + } +}; + +Q_DECLARE_METATYPE(SsmProbeLastConfig_t); + +#endif //SSMPROBELASTCONFIG_H diff --git a/include/model/ssm/dtoInternal/SsmProbeProperties.h b/include/model/ssm/dtoInternal/SsmProbeProperties.h new file mode 100644 index 0000000..b308da8 --- /dev/null +++ b/include/model/ssm/dtoInternal/SsmProbeProperties.h @@ -0,0 +1,198 @@ +#ifndef SSMPROBEPROPERTIES_H +#define SSMPROBEPROPERTIES_H + +#include +#include + +#include "model/databaseManager/dto/ProbeProperties/DbmProbeProperties.h" + +struct SsmProbeProperties_t { + bool linear; + float pitch; + float radius; + int subAzimuthNo; + int subElevationNo; + int elementNo; + float elementWidth; + float elementHeight; + float fieldOfView; + QList impulseResponse; + QList angleValues; + QList focusValues; + QList hiFocusValues; + int multiFocusStep; + QList otiC0Values; + QList > ffcValues; + QList depthData; + QList frequencyValues; + QList hiFrequencyValues; + QList dFrequencyValues; + QList pwFrequencyValues; + QList > criSteeringAngles; + float rxGain; + float txGain; + QList lineDensityValues; + QList dLineDensityValues; + int halfCycleNoValues; + int ffcHalfCycleNoValues; + QList hiHalfCycleNoValues; + QList dopplerHalfCycleNoValues; + QList priExtensionValue; + float dPriExtensionValue; + float txResolution; + float rxResolution; + float mLinesPri; + int simultPwFrameRate; + QList virtualConvexLineDensityValues; + float vcMaxTheta; + QList piValues; + QList hiNames; + QList AtgcB; + QList AtgcD; + QList AtgcPW; + QList AtgcReserve; + + void init(DbmDtoProbeProperties temp) + { + linear = !temp.geometry; + pitch = static_cast(temp.pitch); + radius = static_cast(temp.radius); + subAzimuthNo = temp.subAzimuthNo; + subElevationNo = temp.subElevationNo; + elementNo = temp.elementNo; + elementWidth = static_cast(temp.elementWidth); + elementHeight = static_cast(temp.elementHeight); + fieldOfView = static_cast(temp.fov); + multiFocusStep = temp.multiFocusStep; + rxGain = static_cast(temp.rxGain); + txGain = static_cast(temp.txGain); + halfCycleNoValues = temp.halfCycleNoValues; + ffcHalfCycleNoValues = temp.ffcHalfCycleNoValues; + dPriExtensionValue = static_cast(temp.dPriExtensionValue); + txResolution = static_cast(temp.txResolution); + rxResolution = static_cast(temp.rxResolution); + mLinesPri = static_cast(temp.mLinesPri); + simultPwFrameRate = temp.simultPwFrameRate; + vcMaxTheta = static_cast(temp.vcMaxTheta); + + otiC0Values = temp.otiC0Values; + frequencyValues = temp.frequencyValues; + hiFrequencyValues = temp.hiFrequencyValues; + dFrequencyValues = temp.dFrequencyValues; + pwFrequencyValues = temp.pwFrequencyValues; + hiHalfCycleNoValues = temp.hiHalfCycleNoValues; + dopplerHalfCycleNoValues = temp.dopplerHalfCycleNoValues; + hiNames = temp.hiNames; + + impulseResponse.clear(); + for(auto i = 0; i < temp.impulseResponse.length(); i++) + { + impulseResponse.append(static_cast(temp.impulseResponse[i])); + } + + angleValues.clear(); + for(auto i = 0; i < temp.angleValues.length(); i++) + { + angleValues.append(static_cast(temp.angleValues[i])); + } + + focusValues.clear(); + for(auto i = 0; i < temp.focusValues.length(); i++) + { + focusValues.append(static_cast(temp.focusValues[i])); + } + + hiFocusValues.clear(); + for(auto i = 0; i < temp.hiFocusValues.length(); i++) + { + hiFocusValues.append(static_cast(temp.hiFocusValues[i])); + } + + ffcValues.clear(); + for(auto i = 0; i < temp.ffcValues.length(); i++) + { + QList t; + for(auto j = 0; j < temp.ffcValues[i].length(); j++) + { + t.append(static_cast(temp.ffcValues[i][j])); + } + ffcValues.append(t); + } + + depthData.clear(); + for(auto i = 0; i < temp.depthValues.length(); i++) + { + depthData.append(static_cast(temp.depthValues[i])); + } + + criSteeringAngles.clear(); + for(auto i = 0; i < temp.criSteeringAngles.length(); i++) + { + QList t; + for(auto j = 0; j < temp.criSteeringAngles[i].length(); j++) + { + t.append(static_cast(temp.criSteeringAngles[i][j])); + } + criSteeringAngles.append(t); + } + + lineDensityValues.clear(); + for(auto i = 0; i < temp.lineDensityValues.length(); i++) + { + lineDensityValues.append(static_cast(temp.lineDensityValues[i])); + } + + dLineDensityValues.clear(); + for(auto i = 0; i < temp.dLineDensityValues.length(); i++) + { + dLineDensityValues.append(static_cast(temp.dLineDensityValues[i])); + } + + priExtensionValue.clear(); + for(auto i = 0; i < temp.priExtensionValue.length(); i++) + { + priExtensionValue.append(static_cast(temp.priExtensionValue[i])); + } + + virtualConvexLineDensityValues.clear(); + for(auto i = 0; i < temp.virtualConvexLineDensityValues.length(); i++) + { + virtualConvexLineDensityValues.append( + static_cast(temp.virtualConvexLineDensityValues[i])); + } + + AtgcB.clear(); + for(auto i = 0; i < temp.AtgcB.length(); i++) + { + AtgcB.append(static_cast(temp.AtgcB[i])); + } + + AtgcD.clear(); + for(auto i = 0; i < temp.AtgcD.length(); i++) + { + AtgcD.append(static_cast(temp.AtgcD[i])); + } + + AtgcPW.clear(); + for(auto i = 0; i < temp.AtgcPW.length(); i++) + { + AtgcPW.append(static_cast(temp.AtgcPW[i])); + } + + AtgcReserve.clear(); + for(auto i = 0; i < temp.AtgcReserve.length(); i++) + { + AtgcReserve.append(static_cast(temp.AtgcReserve[i])); + } + + piValues.clear(); + for(auto i = 0; i < temp.piValues.length(); i++) + { + piValues.append(temp.piValues[i] == 1); + } + } +}; + +Q_DECLARE_METATYPE(SsmProbeProperties_t); + +#endif //SSMPROBEPROPERTIES_H diff --git a/include/model/type/CommandValue.h b/include/model/type/CommandValue.h new file mode 100644 index 0000000..2e99693 --- /dev/null +++ b/include/model/type/CommandValue.h @@ -0,0 +1,14 @@ +#ifndef COMMANDVALUE_H +#define COMMANDVALUE_H + + +#include + +class CommandValue +{ +public: + CommandValue() {} + virtual ~CommandValue() {} +}; + +#endif // COMMANDVALUE_H diff --git a/include/model/type/ImageModeCommandValue.h b/include/model/type/ImageModeCommandValue.h new file mode 100644 index 0000000..1611810 --- /dev/null +++ b/include/model/type/ImageModeCommandValue.h @@ -0,0 +1,14 @@ +#ifndef IMAGEMODECOMMANDVALUE_H +#define IMAGEMODECOMMANDVALUE_H + +#include "model/backendImageProcessor/EImageMode.h" +#include "model/type/CommandValue.h" + +class ImageModeCommandValue : public CommandValue +{ +public: + ImageModeCommandValue(EImageMode::eImageMode val) : value{val} {} + EImageMode::eImageMode value; +}; + +#endif // IMAGEMODECOMMANDVALUE_H diff --git a/include/model/type/StringCommandType.h b/include/model/type/StringCommandType.h new file mode 100644 index 0000000..1c36b02 --- /dev/null +++ b/include/model/type/StringCommandType.h @@ -0,0 +1,15 @@ +#ifndef STRINGCOMMANDTYPE_H +#define STRINGCOMMANDTYPE_H + +#include + +#include "model/type/CommandValue.h" + +class StringCommandValue : public CommandValue +{ +public: + StringCommandValue(QString val) : value{val} {} + QString value; +}; + +#endif // STRINGCOMMANDTYPE_H diff --git a/include/model/ultrasoundModule/UsData.h b/include/model/ultrasoundModule/UsData.h new file mode 100644 index 0000000..90e3202 --- /dev/null +++ b/include/model/ultrasoundModule/UsData.h @@ -0,0 +1,41 @@ +#ifndef USDATA_H +#define USDATA_H + +#include +#include +#include + +#include "model/ultrasoundModule/metadata/UsMetadataBag.h" + +#define DEFAULT_COMPRESS_RATIO 3 + +/*************************************************************************************************/ +/** + * @brief The UsData class + * @author Mohamad Mohsem Talaii + * @date 2020/8/1 + */ +/*************************************************************************************************/ +class UsData +{ +private: + bool _compressed = false; + QByteArray _data; + UsMetadataBag _metadata; + +public: + void clear(); + QByteArray getData() const; + void setData(QByteArray data); + UsMetadataBag getMetadataBag() const; + void setMetadataBag(const UsMetadataBag& metadata); + bool isNull() const; + bool compress(int ratio = DEFAULT_COMPRESS_RATIO); + bool uncompress(); + bool compressed(); + unsigned long getSize() const; +}; + +Q_DECLARE_METATYPE(UsData) + +#endif //USDATA_H diff --git a/include/model/ultrasoundModule/UsEventReceiver.h b/include/model/ultrasoundModule/UsEventReceiver.h new file mode 100644 index 0000000..6854fa0 --- /dev/null +++ b/include/model/ultrasoundModule/UsEventReceiver.h @@ -0,0 +1,57 @@ +#ifndef USEVENTRECEIVER_H +#define USEVENTRECEIVER_H + +#include + +#include "model/ultrasoundModule/type/CommandRequest.h" +#include "model/ultrasoundModule/type/CommandResponse.h" +#include "model/ultrasoundModule/type/ECommandResult.h" + +/*************************************************************************************************/ +//Helper macros +#define US_EVENT_RECEIVER(ACCESS) \ + ACCESS: \ + UsEventReceiver* _eventReceiver; \ + public: \ + UsEventReceiver* getEventReceiver() { return _eventReceiver; } \ + +#define US_EVENT_RECEIVER_INSTANTIATE \ + _eventReceiver = new UsEventReceiver(metaObject()->className()) + +/*************************************************************************************************/ +/** + * @brief The class is responsible for receiving commands + * @details This class with help of \see UsEventSender form the communication channel for commands + * between all \see US_MODULE s + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2019/8/5(1398/5/14) + */ +/*************************************************************************************************/ +class UsEventReceiver : public QObject +{ + Q_OBJECT + +private: + QString _ownerName; // In contradiction to the composition rule + // this add a level of safety to app without calling + // actual functions of parent + +public: + explicit UsEventReceiver (QString _ownerName); + + void sendResponse(const CommandRequest &request, + ECommandResult::eCommandResult result); + + void sendResponse(const CommandRequest &request, + ECommandResult::eCommandResult result, + QList args); + +signals: + void commandResponse(const CommandResponse &reponse); + void commandRequest(const CommandRequest &request); + +public slots: + void newCommandRequest(const CommandRequest &request); +}; + +#endif // USEVENTRECEIVER_H diff --git a/include/model/ultrasoundModule/UsEventSender.h b/include/model/ultrasoundModule/UsEventSender.h new file mode 100644 index 0000000..9051e99 --- /dev/null +++ b/include/model/ultrasoundModule/UsEventSender.h @@ -0,0 +1,99 @@ +#ifndef USEVENTSENDER_H +#define USEVENTSENDER_H + +#include +#include + +#include "model/ultrasoundModule/type/CommandRequest.h" +#include "model/ultrasoundModule/type/CommandResponse.h" +#include "model/ultrasoundModule/type/CommandResult.h" +#include "model/ultrasoundModule/type/ECommandType.h" +#include "config/Configuration.h" + +/*************************************************************************************************/ +//Helper macros +#define US_EVENT_SENDER(ACCESS) \ +ACCESS: \ + UsEventSender* _eventSender; \ +public: \ + UsEventSender* getEventSender() { return _eventSender; } \ + +#define US_EVENT_SENDER_INSTANTIATE \ + _eventSender = new UsEventSender(metaObject()->className()) + +/*************************************************************************************************/ +/** + * @brief The class is responsible for sending commands + * @details This class with help of \see UsEventReceiver form the communication channel for commands + * between all \see US_MODULE s + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2019/8/5(1398/5/14) + */ +/*************************************************************************************************/ +class UsEventSender : public QObject +{ + Q_OBJECT + +private: + QList)>, + std::function)> > > _requestTable; + + quint32 _id = 0; + + QString _ownerName; //In contradiction to the composition rule, + //But this add a level of safety to app without calling + //actual functions of parent + + bool _result; + QList _args; + + CommandRequest sendRequest(bool needAck, + ECommandType::eCommandType type, + QString responder, + QList args); + + void success(QList valueList); + void failure(QList valueList); + +public: + explicit UsEventSender(QString _ownerName); + + void sendAsyncRequest(ECommandType::eCommandType type, + QString responder, + QList args, + std::function)> successCallback, + std::function)> failureCallback); + + void sendRequest(ECommandType::eCommandType type, + QVector r, + QVector args, + void (* cb)(void), + std::function successCallback, + std::function failureCallback){ + } + + void sendAsyncRequest(ECommandType::eCommandType type, + QString responder, + QList args); + + void sendRequest(ECommandType::eCommandType type, + QVector responder, + QVector args) { + } + + const CommandResult sendSyncRequest(ECommandType::eCommandType type, + QString responder, + QList args); + +signals: + void commandRequest(const CommandRequest& request); + void exitLoop(); + + //uncrustify off +public slots: + //uncrustify on + void newCommandResponse(const CommandResponse& response); +}; + +#endif //USEVENTSENDER_H diff --git a/include/model/ultrasoundModule/UsHelper.h b/include/model/ultrasoundModule/UsHelper.h new file mode 100644 index 0000000..9b45bdb --- /dev/null +++ b/include/model/ultrasoundModule/UsHelper.h @@ -0,0 +1,29 @@ +#ifndef USHELPER_H +#define USHELPER_H + +#define SINGLETON(NAME) \ + private: \ + static NAME* _instance; \ + static QMutex _mutex; \ + public: \ + static NAME* getInstance() \ + { \ + if(!_instance) \ + { \ + _mutex.lock(); \ + if(!_instance) \ + { \ + _instance = new NAME(); \ + } \ + _mutex.unlock(); \ + } \ + return _instance; \ + } + +#define SINGLETON_DEF(NAME) \ + NAME* NAME::_instance; \ + QMutex NAME::_mutex; + +#define GET_VALUE(REQUEST, INDEX, TYPE) REQUEST.getValueList()[INDEX].value() + +#endif // USHELPER_H diff --git a/include/model/ultrasoundModule/UsModule.h b/include/model/ultrasoundModule/UsModule.h new file mode 100644 index 0000000..ca21d1d --- /dev/null +++ b/include/model/ultrasoundModule/UsModule.h @@ -0,0 +1,129 @@ +#ifndef USMODULE_H +#define USMODULE_H + +#include + +#include "type/CommandRequest.h" +#include "type/CommandResponse.h" +#include "UsEventReceiver.h" +#include "UsEventSender.h" +#include "logger/Logger.h" +#include "UsHelper.h" +#include "UsPacket.h" +#include "utils/Utils.h" + +//forward decleration +class ApplicationStarter; + +//macro defenition +//Place this in each and every class that inherits from UsModule +//so that you dont have to type all this again +#define US_MODULE \ +protected: \ + virtual void commandHandler(const CommandRequest& request) override; \ + virtual void packetHandler(const UsPacket& packet) override; \ + virtual void init() override; \ + virtual void start() override; \ + virtual void afterThreadStart() override; \ +private: \ + template \ + void connectCommandPath() \ + { \ + connect(T::getInstance()->getEventReceiver(), \ + &UsEventReceiver::commandResponse, \ + _eventSender, \ + &UsEventSender::newCommandResponse, Qt::QueuedConnection); \ + connect(_eventSender, \ + &UsEventSender::commandRequest, \ + T::getInstance()->getEventReceiver(), \ + &UsEventReceiver::newCommandRequest, Qt::QueuedConnection); \ + } \ + template \ + void connectDataPath() \ + { \ + connect(this, SIGNAL(packetReady(const UsPacket&)), \ + T::getInstance(), SLOT(newPacket(const UsPacket&))); \ + } \ + + +/*************************************************************************************************/ +/** + * @brief The UsModule class + * @details This class is the bone of our ultrasound framework(if we can call it), it includes all + * the basic functionalities that we expect from a UsModule and provides the developers tools + * and helpers to ease the development of UsModules, + * @note UsModule in its finest defenition, is just a wrapper around some hidden internal + * functionalities, this wrapper provides means of communication(data and command), utilities + * such as logger and helpers. Each UsModule runs in its own thread, has some lifecycle hooks and + * is a singleton + * Some of the features, for example having a special folder layout, was only forced + * to ease further development and readability and was not part of first design goals + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2019/12/15(1398/9/24) + */ +/*************************************************************************************************/ +class UsModule : public QObject +{ + Q_OBJECT + US_EVENT_SENDER(protected) + US_EVENT_RECEIVER(protected) + +private: + void initialize(); + +protected: + virtual void afterThreadStart() = 0; //hook after object is moved to destination thread + virtual void init() = 0; //hook after all USMs created and moved to their threads + virtual void start() = 0; //hook after all USMs gone under init + + virtual void commandHandler(const CommandRequest& request) = 0; + virtual void packetHandler(const UsPacket& packet) = 0; + + void log(ESeverityLevel::eSeverityLevel severity, + ELogID::eLogID logID, QString message); + + void fail(const CommandRequest& request); + void fail(const CommandRequest& request, QList args); + + void pass(const CommandRequest& request); + void pass(const CommandRequest& request, QList args); + + void sendAsyncCommand(ECommandType::eCommandType commandType, QString receiver); + void sendAsyncCommand(ECommandType::eCommandType commandType, + QString receiver, QList args); + void sendAsyncCommand(ECommandType::eCommandType commandType, QString receiver, + std::function)> successCallback, + std::function)> failureCallback); + void sendAsyncCommand(ECommandType::eCommandType commandType, QString receiver, + QList args, + std::function)> successCallback, + std::function)> failureCallback); + CommandResult sendSyncCommand(ECommandType::eCommandType commandType, QString receiver); + CommandResult sendSyncCommand(ECommandType::eCommandType commandType, + QString receiver, QList args); + + void sendData(const UsPacket& data); + +public: + explicit UsModule(QObject*); + virtual ~UsModule() + { + } + +signals: + //To notify the thread to finish + void finished(); + //Will be called when object is moved to destination thread + void ThreadStartUpRoutineFinished(); + //Called to data passing + void packetReady(const UsPacket& packet); + +//uncrustify off +public slots: + void threadStarted(); + void newCommandRequest(const CommandRequest& request); + void newPacket(const UsPacket& packet); +//uncrustify on +}; + +#endif //USMODULE_H diff --git a/include/model/ultrasoundModule/UsPacket.h b/include/model/ultrasoundModule/UsPacket.h new file mode 100644 index 0000000..b2a0222 --- /dev/null +++ b/include/model/ultrasoundModule/UsPacket.h @@ -0,0 +1,58 @@ +#ifndef USPACKET_H +#define USPACKET_H + +#include +#include + +#include "model/ultrasoundModule/UsData.h" + +/*************************************************************************************************/ +/** + * @brief This class is the container for various types of data that may stream throught the system, + * it is a full frame that needs to be processed + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2020/10/04(1399/7/13) + */ +/*************************************************************************************************/ +class UsPacket +{ +private: + UsData _bData; + UsData _mData; + UsData _cData; + UsData _cmData; + UsMetadataBag _metadata; + +public: + UsPacket(); + + void clear(); + + bool hasData() const; + + UsData getBData() const; + void setBData(const UsData& data); + void setBDataMetadataBag(const UsMetadataBag& metadata); + + UsData getMData() const; + void setMData(const UsData& data); + + UsData getCData() const; + void setCData(const UsData& data); + + UsData getCmData() const; + void setCmData(const UsData& data); + + UsMetadataBag getMetadataBag() const; + void setMetadataBag(const UsMetadataBag& metadata); + + unsigned long getSize() const; + + void compress(int ratio = DEFAULT_COMPRESS_RATIO); + void uncompress(); +}; + +Q_DECLARE_METATYPE(UsPacket) +Q_DECLARE_METATYPE(UsPacket*) + +#endif //USPACKET_H diff --git a/include/model/ultrasoundModule/metadata/BMetadata.h b/include/model/ultrasoundModule/metadata/BMetadata.h new file mode 100644 index 0000000..08efa2e --- /dev/null +++ b/include/model/ultrasoundModule/metadata/BMetadata.h @@ -0,0 +1,20 @@ +#ifndef BMETADATA_H +#define BMETADATA_H + +#include "model/ultrasoundModule/metadata/UsBaseMetadata.h" + +class BMetadata : public UsBaseMetadata +{ +public: + quint32 width; + quint32 height; + quint32 frameCounter; + + BMetadata() + { + } +}; + +Q_DECLARE_METATYPE(BMetadata) + +#endif //BMETADATA_H diff --git a/include/model/ultrasoundModule/metadata/BipMetadata.h b/include/model/ultrasoundModule/metadata/BipMetadata.h new file mode 100644 index 0000000..2dfc815 --- /dev/null +++ b/include/model/ultrasoundModule/metadata/BipMetadata.h @@ -0,0 +1,22 @@ +#ifndef BIPMETADATA_H +#define BIPMETADATA_H + +#include "model/ultrasoundModule/metadata/UsBaseMetadata.h" +#include "model/backendImageProcessor/type/EImageMode.h" +#include "model/backendImageProcessor/utils/OpenClHelper.h" +#include "model/enums/EDataType.h" + +class BipMetadata : public UsBaseMetadata +{ +public: + BipMetadata() : UsBaseMetadata("", "") + { + } + + cl::ImageFormat imageFormat; + EDataType::eDataType type; +}; + +Q_DECLARE_METATYPE(BipMetadata) + +#endif //BIPMETADATA_H diff --git a/include/model/ultrasoundModule/metadata/HardwareMetadata.h b/include/model/ultrasoundModule/metadata/HardwareMetadata.h new file mode 100644 index 0000000..54f2a59 --- /dev/null +++ b/include/model/ultrasoundModule/metadata/HardwareMetadata.h @@ -0,0 +1,20 @@ +#ifndef HARDWAREMETADATA_H +#define HARDWAREMETADATA_H + +#include "model/ultrasoundModule/metadata/UsBaseMetadata.h" +#include "model/enums/EDataType.h" + +class HardwareMetadata : public UsBaseMetadata +{ +public: + EDataType::eDataType dataType; + int fps; + + HardwareMetadata() + { + } +}; + +Q_DECLARE_METATYPE(HardwareMetadata) + +#endif //HARDWAREMETADATA_H diff --git a/include/model/ultrasoundModule/metadata/UsBaseMetadata.h b/include/model/ultrasoundModule/metadata/UsBaseMetadata.h new file mode 100644 index 0000000..98ebcfb --- /dev/null +++ b/include/model/ultrasoundModule/metadata/UsBaseMetadata.h @@ -0,0 +1,28 @@ +#ifndef USBASEMETADATA_H +#define USBASEMETADATA_H + +#include + +/*************************************************************************************************/ +/** + * @brief This class is the base class for all metadata through the system + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2020/10/04(1399/7/13) + */ +/*************************************************************************************************/ +class UsBaseMetadata +{ +private: + QString _name; + QString _ownerName; + +public: + UsBaseMetadata(QString name, QString ownerName); + UsBaseMetadata(); + QString getName() const; + QString getOwnerName() const; +}; + +Q_DECLARE_METATYPE(UsBaseMetadata) + +#endif //USBASEMETADATA_H diff --git a/include/model/ultrasoundModule/metadata/UsMetadataBag.h b/include/model/ultrasoundModule/metadata/UsMetadataBag.h new file mode 100644 index 0000000..c376a35 --- /dev/null +++ b/include/model/ultrasoundModule/metadata/UsMetadataBag.h @@ -0,0 +1,36 @@ +#ifndef USMETADATABAG_H +#define USMETADATABAG_H + +#include +#include + +#include "model/ultrasoundModule/metadata/UsBaseMetadata.h" + +/*************************************************************************************************/ +/** + * @brief This class acts as the holder of all metadata for a given type + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2020/10/04(1399/7/13) + */ +/*************************************************************************************************/ +class UsMetadataBag +{ +private: + QList _metadataList; + +public: + UsMetadataBag(); + + template + void appendMetadata(const QVariant& metadata); + template + T getMetadata() const; + template + bool hasMetadata() const; + QList getAllMetadata() const; + template + void deleteMetadata(); + void clear(); +}; + +#endif //USMETADATABAG_H diff --git a/include/model/ultrasoundModule/type/CommandRequest.h b/include/model/ultrasoundModule/type/CommandRequest.h new file mode 100644 index 0000000..4fd7441 --- /dev/null +++ b/include/model/ultrasoundModule/type/CommandRequest.h @@ -0,0 +1,44 @@ +#ifndef COMMANDREQUEST_H +#define COMMANDREQUEST_H + +#include "model/ultrasoundModule/type/ECommandType.h" + +/*************************************************************************************************/ +/** + * @brief The class is responsible for carrying request data + * @details Instead of sending different classes for different signals, this class contains the + * most generic form of data needed + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2019/8/5(1398/5/14) + */ +/*************************************************************************************************/ +class CommandRequest +{ + +private: + QString _sender; + quint32 _ID; + bool _needAck; + ECommandType::eCommandType _commandType; + QString _responder; + QList _valueList; + +public: + CommandRequest() {} + + CommandRequest(QString sender, quint32 ID, bool needAck, + ECommandType::eCommandType type, + QString responder, + QList args); + + QString getSender() const; + quint32 getID() const; + bool needAck() const; + ECommandType::eCommandType getCommandType() const; + QList getValueList() const; + QString getResponder() const; +}; + +Q_DECLARE_METATYPE(CommandRequest) + +#endif // COMMANDREQUEST_H diff --git a/include/model/ultrasoundModule/type/CommandResponse.h b/include/model/ultrasoundModule/type/CommandResponse.h new file mode 100644 index 0000000..c0d3136 --- /dev/null +++ b/include/model/ultrasoundModule/type/CommandResponse.h @@ -0,0 +1,50 @@ +#ifndef COMMANDRESPONSE_H +#define COMMANDRESPONSE_H + +#include + +#include "model/ultrasoundModule/type/ECommandResult.h" + +/*************************************************************************************************/ +/** + * @brief The class is responsible for carrying response data + * @details Instead of sending different classes for different signals, this class contains the + * most generic form of response data needed + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2019/8/5(1398/5/14) + */ +/*************************************************************************************************/ +class CommandResponse +{ + +private: + QString _senderName; + QString _requesterName; + quint32 _requestID; + ECommandResult::eCommandResult _commandResult; + QList _valueList; + +public: + CommandResponse() {} + + CommandResponse(QString senderName, QString requesterName, + quint32 requestID, + ECommandResult::eCommandResult commandResult); + + CommandResponse(QString senderName, QString requesterName, + quint32 requestID, + ECommandResult::eCommandResult commandResult, + QList args); + + + QString getSenderName() const; + QString getRequesterName() const; + quint32 getRequestID() const; + QList getValueList() const; + ECommandResult::eCommandResult getCommandResult() const; +}; + +Q_DECLARE_METATYPE(CommandResponse) +Q_DECLARE_METATYPE(CommandResponse*) + +#endif // COMMANDRESPONSE_H diff --git a/include/model/ultrasoundModule/type/CommandResult.h b/include/model/ultrasoundModule/type/CommandResult.h new file mode 100644 index 0000000..6e634ad --- /dev/null +++ b/include/model/ultrasoundModule/type/CommandResult.h @@ -0,0 +1,31 @@ +#ifndef COMMANDRESULT_H +#define COMMANDRESULT_H + +#include +#include + +/*************************************************************************************************/ +/** + * @brief The class is responsible for carrying response data for sync commands + * @details Instead of sending different classes for different signals, this class contains the + * most generic form of sync response data needed + * @author Hessamoddin Hediyehloo(H-4nd-H) + * @date 2020/8/10(1399/5/20) + */ +/*************************************************************************************************/ +class CommandResult +{ +private: + bool _success; + QList _args; + +public: + CommandResult(bool success, const QList valueList); + + QString name; + + bool isSuccessful() const; + QList getValueList() const; +}; + +#endif //COMMANDRESULT_H diff --git a/include/model/ultrasoundModule/type/ECommandResult.h b/include/model/ultrasoundModule/type/ECommandResult.h new file mode 100644 index 0000000..e290cf6 --- /dev/null +++ b/include/model/ultrasoundModule/type/ECommandResult.h @@ -0,0 +1,66 @@ +#ifndef ECOMMANDRESULT_H +#define ECOMMANDRESULT_H + + +#include + +/** + * @class ElogId ElogId.h "include/ElogId.h" + * @brief The ELogId enumeration class + * @date 07 Aug 2019 + * + * Contains the reference enumerator for + * identificaiton of log messages. + */ + +class ECommandResult : public QObject +{ + Q_OBJECT + +private: + // Private constructor prevent the enumeration class from being instantiated + explicit ECommandResult(QObject *parent = nullptr); +public: + /** + * @brief Log Id Enumerator + * + * Contains the reference enumerator for + * identificaiton of log messages. + */ + enum eCommandResult : quint8 + { + Success, + Failure, + None + }; + Q_ENUM(eCommandResult) + + /** + * @brief enum to string converter + * @param qtEnum Enumerator to be converted to the relevant string + * @return String relevant to the input eLogId enumerator + * @date 07 Aug 2019 + * + * Converts the eLogId enumerator to the relevant string + */ + static QString qtEnumToQString(const eCommandResult qtEnum) + { + return QString(QMetaEnum::fromType().valueToKey(qtEnum)); + } + + /** + * @brief enum to value converter + * @param qtEnum Enumerator to be converted to the relevant value + * @return Identification value relevant to the input eLogId enumerator + * @date 07 Aug 2019 + * + * Converts the eLogId enumerator to the relevant identification number + */ + + static int qtEnumToInt(const eCommandResult qtEnum) + { + return QMetaEnum::fromType().value(qtEnum); + } +}; + +#endif // ECOMMANDRESULT_H diff --git a/include/model/ultrasoundModule/type/ECommandType.h b/include/model/ultrasoundModule/type/ECommandType.h new file mode 100644 index 0000000..7cfe71a --- /dev/null +++ b/include/model/ultrasoundModule/type/ECommandType.h @@ -0,0 +1,505 @@ +#ifndef ECOMMANDTYPE_H +#define ECOMMANDTYPE_H + +#include + +/** + * @class ElogId ElogId.h "include/ElogId.h" + * @brief The ELogId enumeration class + * @date 07 Aug 2019 + * + * Contains the reference enumerator for + * identificaiton of log messages. + */ + +class ECommandType : public QObject +{ + Q_OBJECT + +private: + //Private constructor prevent the enumeration class from being instantiated + explicit ECommandType(QObject* parent = nullptr); + +public: + /** + * @brief Log Id Enumerator + * + * Contains the reference enumerator for + * identificaiton of log messages. + */ + enum eCommandType : quint32 + { + resendParam, + zoomGateSizeChanged, + zoomGateLocationChanged, + bModeSettingChanged, + bModeDisplayChanged, + + mModeSettingChanged, + mModeDisplayChanged, + + simulationChanged, + + consoleBoardChanged, + tgcChanged, + + imageChanged, + scaleChanged, + /**************************************************************************/ + //Menu Parameters + activeTabChanged, + + /**************************************************************************/ + //B Mode Parameters + + grayMapBChanged, + currentGrayMapDataChanged, + tintMapBChanged, + + sriChanged, + sriBypassChanged, + + persistChanged, + + frameFilterChanged, + frameFilterBypassChanged, + + otiChanged, + + criFilterChanged, + criFilterBypassChanged, + + lineFilterChanged, + lineFilterBypassChanged, + + criChanged, + criBypassChanged, + + lineDensityChanged, + + ffcChanged, + + hiChanged, + + frameFilterVisibleChanged, + persistVisibleChanged, + criFilterEnableChanged, + + xlChanged, + sriBChanged, + mirrorChanged, + flipChanged, + + frequencyHiChanged, + aoBChanged, + enhanceChanged, + rejectChanged, + virtualConvexChanged, + dynamicContrastBChanged, + maxAngleChanged, + angleChanged, + + frequencyDiffChanged, + aoDiffChanged, + enhanceDiffChanged, + rejectDiffChanged, + dynamicContrastDiffChanged, + angleDiffChanged, + + /**************************************************************************/ + //M Mode Parameters + + grayMapMChanged, + tintMapMChanged, + + speedMChanged, + bMQualityChanged, + bMSizeChanged, + bMDirectionChanged, + + enhanceMChanged, + rejectMChanged, + dynamicContrastMChanged, + + enhanceMDiffChanged, + rejectMDiffChanged, + dynamicContrastMDiffChanged, + + lineAzimuthMChanged, + + /**************************************************************************/ + //TGC Parameters + + tgcUser1Changed, + tgcUser2Changed, + tgcUser3Changed, + + tgc0Changed, + tgc1Changed, + tgc2Changed, + tgc3Changed, + tgc4Changed, + tgc5Changed, + tgc6Changed, + tgc7Changed, + + tgcNearFieldDiffChanged, + tgcFarFieldDiffChanged, + tgcOveralDiffChanged, + + /**************************************************************************/ + //Cine Parameters + cineDisplayParametersChanged, + playDisplayParametersChanged, + cineSettingChanged, + cineDirectionChanged, + + cineRepeatChanged, + cinePlayChanged, + cineOriginalClipChanged, + + cineStartChanged, + cineEndChanged, + cineSpeedChanged, + cineNumberChanged, + cineCrawl, + + cineStartDiffChanged, + cineEndDiffChanged, + cineSpeedDiffChanged, + cineNumberDiffChanged, + + cineTotalTimeChanged, + cineElapsedTimeChanged, + cineTotalFrameChanged, + cineSavedFrameChanged, + + /**************************************************************************/ + //Joysticks Parameters + joystick1RotaryChanged, + joystick1PushChanged, + + /**************************************************************************/ + //Console Board Parameters + depthDiffChanged, + focusPointsDiffChanged, + focusNumberDiffChanged, + zoomChanged, + + /**************************************************************************/ + //HID Parameters + + mModeEnableChanged, + cModeEnableChanged, + pwModeEnableChanged, + pdModeEnableChanged, + + gainChanged, + gainBDiffChanged, + + gainBChanged, + gainMChanged, + + pulseInverseChanged, + + frequencyChanged, + + //hid parameters + modeChanged, + aoDChanged, + focusNoChanged, + focusChanged, + depthChanged, + hdZoomChanged, + minScanAxChanged, + minScanAzChanged, + maxScanAxChanged, + maxScanAzChanged, + + /**************************************************************************/ + //User Vm + probePage, + + /****************************************************************************/ + /****************************************************************************/ + /****************************************************************************/ + //HID Commands + dualChanged, + quadChanged, + singleChanged, + p1Changed, + p2Changed, + p3Changed, + p4Changed, + exitChanged, + freezeChanged, + pointerChanged, + autoSetChanged, + abcChanged, + fourDChanged, + clearChanged, + threeDChanged, + measChanged, + bodyMarkChanged, + powerChanged, + patientChanged, + utilsChanged, + dvdChanged, + reportChanged, + probeChanged, + availableProbeChanged, + selectProbe, + archiveChanged, + endChanged, + xtdChanged, + bfChanged, + p5Changed, + p6Changed, + + joystick1TopChanged, + joystick2TopChanged, + joystick3TopChanged, + joystick4TopChanged, + joystick5TopChanged, + focusTopChanged, + depthTopChanged, + + joystick1BottomChanged, + joystick2BottomChanged, + joystick3BottomChanged, + joystick4BottomChanged, + joystick5BottomChanged, + focusBottomChanged, + depthBottomChanged, + + joystick1CenterChanged, + joystick2CenterChanged, + joystick3CenterChanged, + joystick4CenterChanged, + joystick5CenterChanged, + focusCenterChanged, + depthCenterChanged, + modePwCenterChanged, + mode2DCenterChanged, + modeMCenterChanged, + modeCCenterChanged, + modePdCenterChanged, + + //trackball + trackballTTChanged, + trackballTBChanged, + trackballTRChanged, + trackballTLChanged, + trackballTTRChanged, + trackballTBRChanged, + trackballTTLChanged, + trackballTBLChanged, + + //joystick + joystick1Changed, + joystick2Changed, + joystick3Changed, + joystick4Changed, + joystick5Changed, + modePwChanged, + mode2DChanged, + modeMChanged, + modeCChanged, + modePdChanged, + + ledChanged, + + /****************************************************************************/ + //simulation + + rxTesterModeChanged, + simulationStartChanged, + simulationStopChanged, + oneshotChanged, + autoIncrementChanged, + workingDirChanged, + + simFolderChanged, + simEnableChanged, + simRunChanged, + + halt, + unhalt, + TestCommand, + init, + start, + pause, + resume, + systemIsUp, + shutingDown, + log, + save, + load, + newFrame, + newPacket, + changeLogPath, + newImage, + stopFeed, //hardware for stop send image + startFeed, //hardware for start send image + + //hardware + bringupHardware, + + selfTest, + + /**********************************************************************/ + //Preset Selection Parameters + prstSelCurrentChanged, + + /**********************************************************************/ + //Main-B Parameters + xBeamCriChanged, + lineDensChanged, + + sri2DChanged, + + examColumnChenged, + harFrq, + aoChanged, + + freezedChanged, + + grayMapSelectChanged, + dynContSelectChanged, + dynContGainChanged, + tintMapSelectChanged, + + /**********************************************************************/ + //Gray Map Parameters + + gmBUser1Changed, + gmBUser2Changed, + gmBUser3Changed, + gmBCurrentChanged, + gmMCurrentChanged, + gmB1XChanged, + gmB2XChanged, + gmB3XChanged, + gmB4XChanged, + gmB5XChanged, + gmB6XChanged, + gmB0YChanged, + gmB1YChanged, + gmB2YChanged, + gmB3YChanged, + gmB4YChanged, + gmB5YChanged, + gmB6YChanged, + gmB7YChanged, + gmM1XChanged, + gmM2XChanged, + gmM3XChanged, + gmM4XChanged, + gmM5XChanged, + gmM6XChanged, + gmM0YChanged, + gmM1YChanged, + gmM2YChanged, + gmM3YChanged, + gmM4YChanged, + gmM5YChanged, + gmM6YChanged, + gmM7YChanged, + + /**********************************************************************/ + //Tint Map Parameters + + tmBCurrentChanged, + tmMCurrentChanged, + + //should be deleted + presetChanged, + + bettaViewChanged, + mSpeedChanged, + changeMode, + + //bool_Enable_Boxes + tgcEnabled, + + newSplashMessage, + changeScenParam, + appStarted, + modulesInited, + modulesStarted, + + scenarioGenUpdate, + + getData, + setData, + + newSimPath, + newSimNumber, + newScenarioRange, + + //****************************************************************************/ + //Evocator + resetMemory, + closeQueue, + + cineCurrentFrameChanged, + cineFreezedChanged, + cineParamChanged,//cine + cinePlayEnabledChanged,// + startCache,//cine + playCache,//cine + pauseCashe,//cine + resetPlayer,//cine + revertPlayer,//cine + selectImage,//cine + fpsChanged,//cine and viewModel + + /**************************************************************************/ + //Image Parameters + sonoBImageWChanged, + sonoBImageHChanged, + + newTrackballConfig, + trackballChangeMode, + + getProbePageConfig, + }; + + Q_ENUM(eCommandType) + + /** + * @brief enum to string converter + * @param qtEnum Enumerator to be converted to the relevant string + * @return String relevant to the input eLogId enumerator + * @date 07 Aug 2019 + * + * Converts the eLogId enumerator to the relevant string + */ + static QString qtEnumToQString(const eCommandType qtEnum) + { + return QString(QMetaEnum::fromType().valueToKey(qtEnum)); + } + + /** + * @brief enum to value converter + * @param qtEnum Enumerator to be converted to the relevant value + * @return Identification value relevant to the input eLogId enumerator + * @date 07 Aug 2019 + * + * Converts the eLogId enumerator to the relevant identification number + */ + + static int qtEnumToInt(const eCommandType qtEnum) + { + return QMetaEnum::fromType().value(qtEnum); + } + + static eCommandType qtStringToEnum(const QString stringEnum) + { + auto&& metaEnum = QMetaEnum::fromType(); + + return static_cast(metaEnum.keyToValue(stringEnum.toUtf8().constData())); + } +}; + +#endif //ECOMMANDTYPE_H diff --git a/include/mvvmCore/MvvmApp.h b/include/mvvmCore/MvvmApp.h new file mode 100644 index 0000000..429ee11 --- /dev/null +++ b/include/mvvmCore/MvvmApp.h @@ -0,0 +1,21 @@ +#ifndef MVVMAPP_H +#define MVVMAPP_H + +#include + +class MvvmApp : public QtMvvm::CoreApp +{ + Q_OBJECT + +public: + explicit MvvmApp(QObject *parent = nullptr); + +protected: + void performRegistrations() override; + int startApp(const QStringList &arguments) override; +}; + +#undef coreApp +#define coreApp static_cast(CoreApp::instance()) + +#endif // MVVMAPP_H diff --git a/include/service/HardwareService.h b/include/service/HardwareService.h new file mode 100644 index 0000000..0aa5b20 --- /dev/null +++ b/include/service/HardwareService.h @@ -0,0 +1,15 @@ +#ifndef HARDWARESERVICE_H +#define HARDWARESERVICE_H + +#include + +class HardwareService +{ +public: + static int32_t readReg(uint32_t address); + static void writeReg(uint32_t address, uint32_t value); + static int32_t* readMem(uint32_t address); + static void writeMem(uint32_t address, uint32_t* value); +}; + +#endif // HARDWARESERVICE_H diff --git a/include/utils/ColorImageProvider.h b/include/utils/ColorImageProvider.h new file mode 100644 index 0000000..bf9da4c --- /dev/null +++ b/include/utils/ColorImageProvider.h @@ -0,0 +1,24 @@ +#ifndef COLORIMAGEPROVIDER_H +#define COLORIMAGEPROVIDER_H + +#include +#include +#include + +class ColorImageProvider : public QQuickImageProvider +{ +public: + ColorImageProvider(); + + QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) override; + void setPic(QPixmap pixmap, quint32 width, quint32 height); + + static ColorImageProvider* getInstance(); + +private: + QPixmap _pixmap; + static ColorImageProvider* _instance; + +}; + +#endif diff --git a/include/utils/PanelChecker.h b/include/utils/PanelChecker.h new file mode 100644 index 0000000..05d849e --- /dev/null +++ b/include/utils/PanelChecker.h @@ -0,0 +1,15 @@ +#ifndef PANELCHECKER_H +#define PANELCHECKER_H + +class PanelChecker +{ +public: + PanelChecker(); + + static bool isKeyboardConnected(); + static bool isMouseConnected(); + static bool isTouchpanelConnected(); + static bool isSecondLcdConnected(); +}; + +#endif //PANELCHECKER_H diff --git a/include/utils/ThreadBinder.h b/include/utils/ThreadBinder.h new file mode 100644 index 0000000..2dde10d --- /dev/null +++ b/include/utils/ThreadBinder.h @@ -0,0 +1,34 @@ +#ifndef THREADBINDER_H +#define THREADBINDER_H + +#include + +#include "model/ultrasoundModule/UsModule.h" +#include "model/csm/utils/MouseEventFilter.h" + +class ThreadBinder : public QObject +{ +public: + static void bind(UsModule* obj, bool eventFilter) + { + auto thread = new QThread(); + obj->moveToThread(thread); + if(eventFilter) + { + auto mousEv = new TrackballMouseEventFilter(); + mousEv->moveToThread(thread); + obj->installEventFilter(mousEv); + } + + //TODO: say this to logger connect(obj, SIGNAL (error(QString)), this, SLOT + //(errorString(QString))); + connect(thread, SIGNAL(started()), obj, SLOT(threadStarted())); + + connect(obj, SIGNAL(finished()), thread, SLOT(quit())); + connect(obj, SIGNAL(finished()), obj, SLOT(deleteLater())); + connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); + thread->start(); + } +}; + +#endif //THREADBINDER_H diff --git a/include/utils/Utils.h b/include/utils/Utils.h new file mode 100644 index 0000000..a660764 --- /dev/null +++ b/include/utils/Utils.h @@ -0,0 +1,40 @@ +#ifndef UTILS_H +#define UTILS_H + +#define CLASS_NAME metaObject()->className() + +#define INSTANCE(OBJ) OBJ::getInstance() + +#define EVENT_SENDER(OBJ) OBJ::getInstance()->getEventSender() +#define EVENT_RECEIVER(OBJ) OBJ::getInstance()->getEventReceiver() + +#define CONNECT_REQ_PATH(SENDER, RECEIVER) \ + connect(EVENT_SENDER(SENDER), &UsEventSender::commandRequest, \ + EVENT_RECEIVER(RECEIVER), &UsEventReceiver::newCommandRequest); \ + connect(EVENT_RECEIVER(RECEIVER), &UsEventReceiver::commandResponse, \ + EVENT_SENDER(SENDER), &UsEventSender::newCommandResponse); + +#define CONNECT_RESPONSE_PATH(RECEIVER) \ + connect(EVENT_RECEIVER(RECEIVER), &UsEventReceiver::commandResponse, \ + _eventSender, &UsEventSender::newCommandResponse) + +#define CONNECT_RESULT_PATH(SENDER, RECEIVER) \ + connect(EVENT_SENDER(SENDER), \ + &UsEventSender::commandResult, \ + _eventReceiver, &UsEventReceiver::newCommandResult) + +#define GET_COMMAND_TYPE(REQUEST) REQUEST.getCommandType() +#define COMMAND_TYPE(COMMAND) ECommandType::COMMAND +#define CHECK_COMMAND_TYPE(REQUEST, COMMAND) \ + GET_COMMAND_TYPE(REQUEST) == COMMAND_TYPE(COMMAND) + +#define SND_REQ_NO_ARG(command, ...) \ + _eventSender->sendRequest(ECommandType::command, \ + QVector({__VA_ARGS__}), \ + QVector()) + +//#define GET_VALUE(REQUEST, INDEX, TYPE) REQUEST.getValueList()[INDEX].value() + +#define PATH_CONCAT(P1, P2) P1 + "/" + P2 + +#endif // UTILS_H diff --git a/include/viewModel/BaseViewModel.h b/include/viewModel/BaseViewModel.h new file mode 100644 index 0000000..60e16eb --- /dev/null +++ b/include/viewModel/BaseViewModel.h @@ -0,0 +1,102 @@ +#ifndef BASEVIEWMODEL_H +#define BASEVIEWMODEL_H + +#include +#include + +#include "model/ultrasoundModule/UsHelper.h" +#include "model/ultrasoundModule/UsEventSender.h" +#include "model/ultrasoundModule/UsEventReceiver.h" + +#include "model/databaseManager/type/EDatabaseRequest.h" + +#include "viewModel/utils/AutoProperty.h" +#include "viewModel/utils/UsMultiButton.h" +#include "viewModel/utils/UsSpinBox.h" +#include "viewModel/utils/UsSwitchButton.h" +#include "viewModel/utils/UsJoystick.h" +#include "viewModel/utils/UsRadioButton.h" +#include "viewModel/utils/UsInfoBox.h" +#include "viewModel/utils/UsTrackball.h" +#include "viewModel/utils/UsList.h" +#include "viewModel/utils/UsImage.h" + +//macro defenition +//Place this in each and every class that inherits from BaseViewModel +//so that you dont have to type all this again +//uncrustify off +#define US_VIEW_MODEL(VIEW_MODEL_NAME) \ +private: \ + void prepareData() override; \ + void sendData() override; \ + void setInitialValue() override; \ + void turnOnMinimalMode() override; \ + void turnOffMinimalMode() override; \ + explicit VIEW_MODEL_NAME(); \ +private slots: \ + void newCommandRequest(const CommandRequest& request); \ +public: \ + virtual void init() override; \ + + +#define APPLY_DIFF_COMMAND(PROPERTY) \ +auto diffValue = GET_VALUE(request, 0, qint16); \ +auto nextValue = getNextValue(PROPERTY() + diffValue, 0, PROPERTY ## Values().length() - 1); \ +PROPERTY(nextValue); \ + +//uncrustify on + +/*************************************************************************************************/ +class BaseViewModel : public QtMvvm::ViewModel +{ + Q_OBJECT + US_EVENT_SENDER(protected) + US_EVENT_RECEIVER(protected) + +private: + int _awaitingSend; + bool isSendingAllowed(); + + virtual void setInitialValue() = 0; + virtual void prepareData() = 0; + virtual void sendData() = 0; + + virtual void turnOnMinimalMode() = 0; + virtual void turnOffMinimalMode() = 0; + +protected: + void allowSending(); + void blockSending(); + + virtual void send() final; + + virtual QList arithmeticSeries(int start, int end, int step) final; + + virtual QList arithmeticSeries(float start, + float end, + float step, + int precision) final; + + virtual CommandResult sendDataIntoDatabase(EDatabaseRequest::eDatabaseRequest request, + const QList args) final; + virtual CommandResult requestDataFromDatabase(EDatabaseRequest::eDatabaseRequest request, + const QList args) final; + + template + T translateDatabaseData(const QList args, const quint32 index) { + return args[index].value(); + } + +public: + explicit BaseViewModel(); + + void start(); + virtual void init() = 0; + + void changeMode(bool minimal); + + virtual int getNextValue(const int estimatedValue, const int lowerBound, + const int upperBound) final; +}; + +#endif //BASEVIEWMODEL_H diff --git a/include/viewModel/MainViewModel.h b/include/viewModel/MainViewModel.h new file mode 100644 index 0000000..90e9314 --- /dev/null +++ b/include/viewModel/MainViewModel.h @@ -0,0 +1,96 @@ +#ifndef MAINVIEWMODEL_H +#define MAINVIEWMODEL_H + +#include +#include +#include + +#include "utils/ColorImageProvider.h" +#include "model/ultrasoundModule/UsEventSender.h" +#include "model/ultrasoundModule/UsEventReceiver.h" +#include "viewModel/utils/AutoProperty.h" + +#include "viewModel/probe/ProbeViewModel.h" + +#include "viewModel/bMode/display/BModeDisplayViewModel.h" +#include "viewModel/bMode/setting/BModeSettingViewModel.h" + +#include "viewModel/mMode/display/MModeDisplayViewModel.h" +#include "viewModel/mMode/setting/MModeSettingViewModel.h" + +#include "viewModel/cine/display/CineDisplayViewModel.h" +#include "viewModel/cine/setting/CineSettingViewModel.h" + +#include "viewModel/tgc/TgcViewModel.h" +#include "viewModel/simulation/SimulationViewModel.h" + +#include "viewModel/trackball/TrackballViewModel.h" + +#include "viewModel/image/ImageViewModel.h" + +#include "viewModel/user/UserViewModel.h" + +class MainViewModel : public QtMvvm::ViewModel +{ + Q_OBJECT + US_EVENT_SENDER(private) + US_EVENT_RECEIVER(private) + +private: + static MainViewModel* _instance; + + void init(); + void start(); + /**************************************************************************/ + + //ViewModel + + US_PROPERTY_VIEW_ONLY(ProbeViewModel*, probeViewModel, + ProbeViewModel::getInstance()) + + US_PROPERTY_VIEW_ONLY(BModeDisplayViewModel*, bModeDisplayViewModel, + BModeDisplayViewModel::getInstance()) + + US_PROPERTY_VIEW_ONLY(BModeSettingViewModel*, bModeSettingViewModel, + BModeSettingViewModel::getInstance()) + + US_PROPERTY_VIEW_ONLY(CineDisplayViewModel*, cineDisplayViewModel, + CineDisplayViewModel::getInstance()) + + US_PROPERTY_VIEW_ONLY(CineSettingViewModel*, cineSettingViewModel, + CineSettingViewModel::getInstance()) + + US_PROPERTY_VIEW_ONLY(TgcViewModel*, tgcViewModel, + TgcViewModel::getInstance()) + + US_PROPERTY_VIEW_ONLY(SimulationViewModel*, simulationViewModel, + SimulationViewModel::getInstance()) + + US_PROPERTY_VIEW_ONLY(TrackballViewModel*, trackballViewModel, + TrackballViewModel::getInstance()) + + US_PROPERTY_VIEW_ONLY(ImageViewModel*, imageViewModel, + ImageViewModel::getInstance()) + + US_PROPERTY_VIEW_ONLY(MModeDisplayViewModel*, mModeDisplayViewModel, + MModeDisplayViewModel::getInstance()) + + US_PROPERTY_VIEW_ONLY(MModeSettingViewModel*, mModeSettingViewModel, + MModeSettingViewModel::getInstance()) + + US_PROPERTY_VIEW_ONLY(UserViewModel*, userViewModel, + UserViewModel::getInstance()) + +public: + Q_INVOKABLE explicit MainViewModel(QObject* parent = nullptr); + + Q_INVOKABLE void close(); + + static MainViewModel* getInstance(); + //uncrustify off +private slots: + //uncrustify on + void newCommandRequest(const CommandRequest& request); +}; + +#endif //MAINVIEWMODEL_H diff --git a/include/viewModel/UsmMimic.h b/include/viewModel/UsmMimic.h new file mode 100644 index 0000000..8def8bb --- /dev/null +++ b/include/viewModel/UsmMimic.h @@ -0,0 +1,34 @@ +#ifndef USMMIMIC_H +#define USMMIMIC_H + +#define INSTANCE(OBJ) OBJ::getInstance() + +#define CONNECT_COMMAND_LINE(SENDER, RECEIVER) \ + do { \ + connect(EVENT_SENDER(SENDER), &UsEventSender::commandRequest, \ + EVENT_RECEIVER(RECEIVER), &UsEventReceiver::newCommandRequest); \ + connect(EVENT_RECEIVER(RECEIVER), &UsEventReceiver::commandResponse, \ + EVENT_SENDER(SENDER), &UsEventSender::newCommandResponse); \ + } while(0) + +#define SEND_FORGET_ASYNC(COMMAND, RECEIVER, ARGS) \ + _eventSender->sendAsyncRequest(ECommandType::COMMAND, RECEIVER, ARGS) + +#define SEND_FORGET_ASYNC_NO_ARG(COMMAND, RECEIVER) \ + _eventSender->sendAsyncRequest(ECommandType::COMMAND, RECEIVER, {}) + +#define SEND_ASYNC(COMMAND, RECEIVER, ARGS, SUCCESS, FAILURE) \ + _eventSender->sendAsyncRequest(ECommandType::COMMAND, RECEIVER, ARGS, SUCCESS, FAILURE) + +#define SEND_ASYNC_NO_ARG(COMMAND, RECEIVER, SUCCESS, FAILURE) \ + _eventSender->sendAsyncRequest(ECommandType::COMMAND, RECEIVER, {}, SUCCESS, FAILURE) + +#define SEND_SYNC(COMMAND, RECEIVER, ARGS) \ + _eventSender->sendSyncRequest(ECommandType::COMMAND, RECEIVER, ARGS) + +#define SEND_SYNC_NO_ARG(COMMAND, RECEIVER) \ + _eventSender->sendSyncRequest(ECommandType::COMMAND, RECEIVER, {}) + +#define GET_VALUE(REQUEST, INDEX, TYPE) REQUEST.getValueList()[INDEX].value() + +#endif // USMMIMIC_H diff --git a/include/viewModel/bMode/display/BModeDisplayViewModel.h b/include/viewModel/bMode/display/BModeDisplayViewModel.h new file mode 100644 index 0000000..668772b --- /dev/null +++ b/include/viewModel/bMode/display/BModeDisplayViewModel.h @@ -0,0 +1,125 @@ +#ifndef BMODEDISPLAYVIEWMODEL_H +#define BMODEDISPLAYVIEWMODEL_H + +#include "viewModel/BaseViewModel.h" + +#include "viewModel/bMode/display/DataBModeDisplay.h" + +#include "viewModel/bMode/display/dtoInternal/BModeDisplayPresetValues.h" + +#include "model/databaseManager/type/EDatabaseRequest.h" + +class BModeDisplayViewModel : public BaseViewModel +{ + Q_OBJECT + US_VIEW_MODEL(BModeDisplayViewModel) + SINGLETON(BModeDisplayViewModel) + +//uncrustify off +public slots: +//uncrustify on + void saveGrayMap(int saveButtonNumber); + +private: + QList > _grayMapData; + + DataBModeDisplay_t _data; + BModeDisplayPresetValues_t _presetValues; + + void setGrayMapData(); + + void applyPreset(); + + void setGrayMapData(int index, QList userGrayMap); + + void getGrayMapData(); + + void nobHandle(); + + void plotByNobs(); + + void setNobs(); + + US_LIST(int, currentGrayMapData) + + //Gray Map + US_POPUP_BUTTON_CUSTOM_SETTER(grayMap, "Gray Map", + (QList({"1", "2", "3", "4", "5", "6", + "7", "8", "9", "10", "11", "12", + "13", "14", "15", "16", "17", "18", + "U1", "U2", "U3"})), + "", "", true, true, 0, true, false) + + //Default Buttons + US_SIMPLE_BUTTON(grayMap0, "1", "qrc:/UI/Images/GrayMap/grayMap0.svg", true, true) + US_SIMPLE_BUTTON(grayMap1, "2", "qrc:/UI/Images/GrayMap/grayMap1.svg", true, true) + US_SIMPLE_BUTTON(grayMap2, "3", "qrc:/UI/Images/GrayMap/grayMap2.svg", true, true) + US_SIMPLE_BUTTON(grayMap3, "4", "qrc:/UI/Images/GrayMap/grayMap3.svg", true, true) + US_SIMPLE_BUTTON(grayMap4, "5", "qrc:/UI/Images/GrayMap/grayMap4.svg", true, true) + US_SIMPLE_BUTTON(grayMap5, "6", "qrc:/UI/Images/GrayMap/grayMap5.svg", true, true) + US_SIMPLE_BUTTON(grayMap6, "7", "qrc:/UI/Images/GrayMap/grayMap6.svg", true, true) + US_SIMPLE_BUTTON(grayMap7, "8", "qrc:/UI/Images/GrayMap/grayMap7.svg", true, true) + US_SIMPLE_BUTTON(grayMap8, "9", "qrc:/UI/Images/GrayMap/grayMap8.svg", true, true) + US_SIMPLE_BUTTON(grayMap9, "10", "qrc:/UI/Images/GrayMap/grayMap9.svg", true, true) + US_SIMPLE_BUTTON(grayMap10, "11", "qrc:/UI/Images/GrayMap/grayMap10.svg", true, true) + US_SIMPLE_BUTTON(grayMap11, "12", "qrc:/UI/Images/GrayMap/grayMap11.svg", true, true) + US_SIMPLE_BUTTON(grayMap12, "13", "qrc:/UI/Images/GrayMap/grayMap12.svg", true, true) + US_SIMPLE_BUTTON(grayMap13, "14", "qrc:/UI/Images/GrayMap/grayMap13.svg", true, true) + US_SIMPLE_BUTTON(grayMap14, "15", "qrc:/UI/Images/GrayMap/grayMap14.svg", true, true) + US_SIMPLE_BUTTON(grayMap15, "16", "qrc:/UI/Images/GrayMap/grayMap15.svg", true, true) + US_SIMPLE_BUTTON(grayMap16, "17", "qrc:/UI/Images/GrayMap/grayMap16.svg", true, true) + US_SIMPLE_BUTTON(grayMap17, "18", "qrc:/UI/Images/GrayMap/grayMap17.svg", true, true) + + //User Buttons + US_SIMPLE_BUTTON(grayMapUser1, "User 1", "", true, true) + US_SIMPLE_BUTTON(grayMapUser2, "User 2", "", true, true) + US_SIMPLE_BUTTON(grayMapUser3, "User 3", "", true, true) + + //Save Buttons + US_SIMPLE_BUTTON(grayMapSaveAs, "Save As", "", true, true) + + //Tint Map + US_SPIN_BOX(tintMap, "Tint Map", + (QList({"Off", "Candle", "Sepia", "Soft Sepia", "Blue", + "Copper", "Standard", "Clear", + "Cool Blue", "Ice", "Sepia 1"})), + "", "", true, true, 0) + + US_SIMPLE_BUTTON(tintMap0, "Off", "transparent", true, true) + US_SIMPLE_BUTTON(tintMap1, "Candle", "#a95200", true, true) + US_SIMPLE_BUTTON(tintMap2, "Sepia", "#935f30", true, true) + US_SIMPLE_BUTTON(tintMap3, "Soft Sepia", "#775731", true, true) + US_SIMPLE_BUTTON(tintMap4, "Blue", "#245d7b", true, true) + US_SIMPLE_BUTTON(tintMap5, "Copper", "#664131", true, true) + US_SIMPLE_BUTTON(tintMap6, "Standard", "#52555b", true, true) + US_SIMPLE_BUTTON(tintMap7, "Clear", "#4e5760", true, true) + US_SIMPLE_BUTTON(tintMap8, "Cool Blue", "#475669", true, true) + US_SIMPLE_BUTTON(tintMap9, "Ice", "#48586f", true, true) + US_SIMPLE_BUTTON(tintMap10, "Sepia 1", "#935f30", true, true) + + US_PROPERTY(int, posX0, 0) + US_PROPERTY_CUSTOM_SETTER(int, posY0, 0) + + US_PROPERTY_CUSTOM_SETTER(int, posX1, 36) + US_PROPERTY_CUSTOM_SETTER(int, posY1, 36) + + US_PROPERTY_CUSTOM_SETTER(int, posX2, 73) + US_PROPERTY_CUSTOM_SETTER(int, posY2, 73) + + US_PROPERTY_CUSTOM_SETTER(int, posX3, 109) + US_PROPERTY_CUSTOM_SETTER(int, posY3, 109) + + US_PROPERTY_CUSTOM_SETTER(int, posX4, 146) + US_PROPERTY_CUSTOM_SETTER(int, posY4, 146) + + US_PROPERTY_CUSTOM_SETTER(int, posX5, 182) + US_PROPERTY_CUSTOM_SETTER(int, posY5, 182) + + US_PROPERTY_CUSTOM_SETTER(int, posX6, 219) + US_PROPERTY_CUSTOM_SETTER(int, posY6, 219) + + US_PROPERTY(int, posX7, 255) + US_PROPERTY_CUSTOM_SETTER(int, posY7, 255) +}; + +#endif //BMODEDISPLAYVIEWMODEL_H diff --git a/include/viewModel/bMode/display/DataBModeDisplay.h b/include/viewModel/bMode/display/DataBModeDisplay.h new file mode 100644 index 0000000..be84c4a --- /dev/null +++ b/include/viewModel/bMode/display/DataBModeDisplay.h @@ -0,0 +1,15 @@ +#ifndef DATABMODEDISPLAY_H +#define DATABMODEDISPLAY_H + +#include +#include + +typedef struct DataBModeDisplay_t +{ + int tintmap; + QList graymap; +} DataBModeDisplay_t; + +Q_DECLARE_METATYPE(DataBModeDisplay_t); + +#endif //DATABMODEDISPLAY_H diff --git a/include/viewModel/bMode/display/PchipInterp.h b/include/viewModel/bMode/display/PchipInterp.h new file mode 100644 index 0000000..4accc13 --- /dev/null +++ b/include/viewModel/bMode/display/PchipInterp.h @@ -0,0 +1,251 @@ +#ifndef PCHIPINTERP_H +#define PCHIPINTERP_H + +#include +#include + +// +//File: pchipInterp.cpp +// +//MATLAB Coder version : 4.1 +//C/C++ source code generated on : 24-Dec-2020 17:26:59 +// + +//Include Files +#include +#include +#include + +//Function Definitions + +//Arguments : float d1 +//float d2 +//float h1 +//float h2 +//Return Type : float +// + +float exteriorSlope(float d1, float d2, float h1, float h2) +{ + float s; + float signd1; + float signs; + s = ((2.0F * h1 + h2) * d1 - h1 * d2) / (h1 + h2); + signd1 = d1; + if(d1 < 0.0F) + { + signd1 = -1.0F; + } + else + if(d1 > 0.0F) + { + signd1 = 1.0F; + } + else + { + if(d1 == 0.0F) + { + signd1 = 0.0F; + } + } + + signs = s; + if(s < 0.0F) + { + signs = -1.0F; + } + else + if(s > 0.0F) + { + signs = 1.0F; + } + else + { + if(s == 0.0F) + { + signs = 0.0F; + } + } + + if(signs != signd1) + { + s = 0.0F; + } + else + { + signs = d2; + if(d2 < 0.0F) + { + signs = -1.0F; + } + else + if(d2 > 0.0F) + { + signs = 1.0F; + } + else + { + if(d2 == 0.0F) + { + signs = 0.0F; + } + } + + if((signd1 != signs) && ((float)fabs((double)s) > (float)fabs((double)(3.0F * + d1)))) + { + s = 3.0F * d1; + } + } + + return s; +} + +//Function Definitions + +// +//Arguments : const float x[8] +//const float y[8] +//float p[256] +//Return Type : void + +void pchipInterp(const float x[8], const float y[8], float p[256]) +{ + int k; + float h[7]; + float del[7]; + float slopes[8]; + float dzzdx; + float hs; + float hs3; + float w1; + int low_i; + float pp_coefs[28]; + int low_ip1; + int high_i; + int mid_i; + for(k = 0; k < 7; k++) + { + h[k] = x[k + 1] - x[k]; + } + + for(k = 0; k < 7; k++) + { + del[k] = (y[k + 1] - y[k]) / h[k]; + } + + for(k = 0; k < 6; k++) + { + dzzdx = h[1 + k]; + hs = h[k] + dzzdx; + hs3 = 3.0F * hs; + w1 = (h[k] + hs) / hs3; + dzzdx = (dzzdx + hs) / hs3; + slopes[1 + k] = 0.0F; + if(del[k] < 0.0F) + { + if(del[1 + k] <= del[k]) + { + slopes[1 + k] = del[k] / (w1 * (del[k] / del[1 + k]) + dzzdx); + } + else + { + if(del[1 + k] < 0.0F) + { + slopes[1 + k] = del[1 + k] / (w1 + dzzdx * (del[1 + k] / del[k])); + } + } + } + else + { + if(del[k] > 0.0F) + { + hs = del[1 + k]; + if(hs >= del[k]) + { + slopes[1 + k] = del[k] / (w1 * (del[k] / hs) + dzzdx); + } + else + { + if(hs > 0.0F) + { + slopes[1 + k] = hs / (w1 + dzzdx * (hs / del[k])); + } + } + } + } + } + + slopes[0] = exteriorSlope(del[0], del[1], h[0], h[1]); + slopes[7] = exteriorSlope(del[6], del[5], h[6], h[5]); + for(k = 0; k < 7; k++) + { + dzzdx = (del[k] - slopes[k]) / h[k]; + hs = (slopes[k + 1] - del[k]) / h[k]; + pp_coefs[k] = (hs - dzzdx) / h[k]; + pp_coefs[k + 7] = 2.0F * dzzdx - hs; + pp_coefs[k + 14] = slopes[k]; + pp_coefs[k + 21] = y[k]; + } + + for(k = 0; k < 256; k++) + { + low_i = 0; + low_ip1 = 2; + high_i = 8; + while(high_i > low_ip1) + { + mid_i = ((low_i + high_i) + 1) >> 1; + if(((float)k + 1.0F) - 1.0F >= x[mid_i - 1]) + { + low_i = mid_i - 1; + low_ip1 = mid_i + 1; + } + else + { + high_i = mid_i; + } + } + + dzzdx = (((float)k + 1.0F) - 1.0F) - x[low_i]; + p[k] = dzzdx * (dzzdx * (dzzdx * pp_coefs[low_i] + pp_coefs[low_i + 7]) + + pp_coefs[low_i + 14]) + pp_coefs[low_i + 21]; + } +} + +QList interpolator( + const int posX1, const int posX2, const int posX3, const int posX4, + const int posX5, const int posX6, + const int posY0, const int posY1, const int posY2, const int posY3, + const int posY4, const int posY5, const int posY6, const int posY7) +{ + float x[8] = {0.0, static_cast(posX1), static_cast(posX2), + static_cast(posX3), static_cast(posX4), static_cast(posX5), + static_cast(posX6), 255.0}; + + float y[8] = {static_cast(posY0), static_cast(posY1), static_cast(posY2), + static_cast(posY3), static_cast(posY4), static_cast(posY5), + static_cast(posY6), static_cast(posY7)}; + + float p[256]; + + pchipInterp(x, y, p); + + int pInt[256]; + for(int i = 0; i < 256; i++) + { + pInt[i] = static_cast(p[i]); + } + + std::list pList; + for(int i: pInt) + { + pList.push_back(i); + } + + QList interpolatedData = QList::fromStdList(pList); + + return interpolatedData; +} + +#endif //PCHIPINTERP_H diff --git a/include/viewModel/bMode/display/dtoInternal/BModeDisplayPresetValues.h b/include/viewModel/bMode/display/dtoInternal/BModeDisplayPresetValues.h new file mode 100644 index 0000000..93a30d9 --- /dev/null +++ b/include/viewModel/bMode/display/dtoInternal/BModeDisplayPresetValues.h @@ -0,0 +1,20 @@ +#ifndef BMODEDISPLAYPRESETVALUES_T_H +#define BMODEDISPLAYPRESETVALUES_T_H + +#include +#include + +#include "model/ssm/dtoInternal/SsmPresetValues.h" + +struct BModeDisplayPresetValues_t { + int grayMap; + int tintMap; + + void init(SsmPresetValues_t temp) + { + grayMap = temp.grayMapB; + tintMap = temp.tintMapB; + } +}; + +#endif //BMODEDISPLAYPRESETVALUES_T_H diff --git a/include/viewModel/bMode/setting/BModeSettingViewModel.h b/include/viewModel/bMode/setting/BModeSettingViewModel.h new file mode 100644 index 0000000..140ea81 --- /dev/null +++ b/include/viewModel/bMode/setting/BModeSettingViewModel.h @@ -0,0 +1,138 @@ +#ifndef BMODESETTINGVIEWMODEL_H +#define BMODESETTINGVIEWMODEL_H + +#include "viewModel/BaseViewModel.h" + +#include "viewModel/bMode/setting/DataBModeSetting.h" +#include "viewModel/bMode/setting/dtoInternal/BModeSettingProbePropertes.h" +#include "viewModel/bMode/setting/dtoInternal/BModeSettingPresetValues.h" + +#include "model/backendImageProcessor/type/EImageMode.h" + +class BModeSettingViewModel : public BaseViewModel +{ + Q_OBJECT + US_VIEW_MODEL(BModeSettingViewModel) + SINGLETON(BModeSettingViewModel) + +private: + DataBModeSetting_t _data; + + BModeSettingProbeProperties_t _prbProps; + BModeSettingPresetValues_t _presetValues; + + EImageMode::eImageMode _imageMode; + + QList _depthList; + + bool _freezed; + + bool getPiValue(); + + double degree2Rad(int angle); + + bool isProbeLinear(); + + void setCriFilterEnable(); + + void setFrequencyEnable(); + + bool canEnableCriFilter(); + + bool canEnableFrequency(); + + int getRejectTrueValue(); + + void setAngle(int diff); + + bool getCriEnableStatus(); + + int getRoundedPreviousAngle(int diff); + + void setProbeDependentParams(); + + void setFrequencyValues(); + + void setAngleVisibility(); + + void checkAngleValidity(); + + void setFocusNumberValidValues(); + void setFocusPointsValidValues(); + int getMaxFocusPoints(int focusLenght, int focusNumber, int focusStep); + + void setFocusPointsValuesForHi(); + void setFocusPointsValuesForFfc(); + void setFocusPointsValues(); + + void setDepthValues(); + + QList getNoneHiFreqNames(); + QList getHiFreqNames(); + + void applyPreset(); + +/**************************************************************************************************/ + + US_MULTI_BUTTON(sri, "SRI", (QList({""})), "", "", true, true, 0, false) + + US_SPIN_BOX(persist, "Persist", (QList({""})), "", "", true, false, 1) + + US_MULTI_BUTTON(frameFilter, "Frame Filter", (QList({""})), "", "", + true, true, 0, false) + + US_SPIN_BOX(oti, "OTI", (QList({"Solid", "Normal", "Adipose", "Cystic"})), + "", "", true, true, 0) + + US_MULTI_BUTTON(criFilter, "CRI Filter", (QList({"Low", "Mid", "High"})), + "", "", true, true, 0, false) + + US_MULTI_BUTTON(lineFilter, "Line Filter", (QList({"Low", "High"})), + "", "", true, true, 0, false) + + US_MULTI_BUTTON_CUSTOM_SETTER_BYPASS_ONLY(cri, "CRI", QList({""}), + "", "", true, true, 0, false) + + US_SPIN_BOX(lineDensity, "Line Dens.", (QList({"Low", "Norm", "High"})), + "", "", true, true, 0) + + US_SWITCH_BUTTON_CUSTOM_SETTER(ffc, "FFC", "", true, true, false) + + US_SWITCH_BUTTON_CUSTOM_SETTER(hi, "HI", "", true, true, false) + + US_SWITCH_BUTTON(virtualConvex, "Virtual Convex", "", true, true, false) + + US_SWITCH_BUTTON_CUSTOM_SETTER(maxAngle, "Max Angle", "", true, true, false) + + US_SPIN_BOX_CUSTOM_SETTER(frequency, "Frq", {""}, "", "", true, true, 0) + + US_SPIN_BOX(ao, "AO", (QList({""})), "", "%", true, true, 0) + + US_SPIN_BOX(enhance, "Enhance", (QList({"Off", "1", "2", "3", "4", "5"})), + "", "", true, true, 0) + + US_SPIN_BOX(reject, "Reject", (QList({""})), "", "", true, true, 0) + + US_SPIN_BOX(dynamicContrast, "Dy.Cnt.", (QList({""})), "", "", true, true, 0) + + US_JOYSTICK_SIMPLE(angle, "Angle", true, true, 0) + + US_PROPERTY(bool, pi, true) + + US_INFO_BOX(depth, "Depth", (QList({""})), "", "cm", true, true, 0) + + US_INFO_BOX(focusPoints, "Foc.Pnt.", (QList({""})), + "", "", true, true, 0) + + US_INFO_BOX_CUSTOM_SETTER(focusNumber, "Foc.Num.", (QList({""})), + "", "", true, true, 0) + + US_INFO_BOX(gainB, "Gain", (QList({""})), "", "dB", true, true, 0) + + US_INFO_BOX_BOOL(hdZoom, "HD.Zoom", true, true, false) + +public: + void freezeChanged(bool freeze); +}; + +#endif //BMODESETTINGVIEWMODEL_H diff --git a/include/viewModel/bMode/setting/DataBModeSetting.h b/include/viewModel/bMode/setting/DataBModeSetting.h new file mode 100644 index 0000000..98af7d6 --- /dev/null +++ b/include/viewModel/bMode/setting/DataBModeSetting.h @@ -0,0 +1,44 @@ +#ifndef DATABMODESETTING_H +#define DATABMODESETTING_H + +#include + +typedef struct DataBModeSetting_t +{ + quint32 sri; + + quint32 persist; + quint32 frameFilter; + + quint32 oti; + + quint32 criFilter; + quint32 cri; + + quint32 lineFilter; + quint32 lineDensity; + + bool ffc; + bool hi; + + quint32 ao; + quint32 frequency; + float angle; + + quint32 enhance; + quint32 reject; + quint32 dynamicContrast; + + bool virtualConvex; + bool pi; + + float depth; + int focusPoints; + int focusNumber; + int gainB; + bool hdZoom; +} DataBModeSetting_t; + +Q_DECLARE_METATYPE(DataBModeSetting_t); + +#endif //DATABMODESETTING_H diff --git a/include/viewModel/bMode/setting/dtoInternal/BModeSettingPresetValues.h b/include/viewModel/bMode/setting/dtoInternal/BModeSettingPresetValues.h new file mode 100644 index 0000000..d507612 --- /dev/null +++ b/include/viewModel/bMode/setting/dtoInternal/BModeSettingPresetValues.h @@ -0,0 +1,66 @@ +#ifndef BMODESETTINGPRESETVALUES_T_H +#define BMODESETTINGPRESETVALUES_T_H + +#include +#include + +#include "model/ssm/dtoInternal/SsmPresetValues.h" + +struct BModeSettingPresetValues_t { + int angle; + int ao; + int criFilter; + int depth; + int dynContB; + int lineDensity; + int rejectB; + int frameFilter; + bool lineFilterBypass; + int lineFilter; + int criLineFilter; + int cri; + int enhanceB; + int gainB; + int focusNumber; + int persist; + int focus; + bool sriBypass; + int sri; + int oti; + int frequency; + bool hi; + bool ffc; + bool virtualConvex; + bool criBypass; + + void init(SsmPresetValues_t temp) + { + angle = temp.angle; + ao = 100 + temp.apcTxPower; + criFilter = temp.criFilter; + depth = temp.depth; + dynContB = temp.dynContB; + lineDensity = temp.lineDensity; + rejectB = temp.rejectB; + frameFilter = temp.framFilter; + lineFilterBypass = lineFilter == 0; + lineFilter = temp.lineFilter > 0 ? temp.lineFilter - 1 : temp.lineFilter; + criLineFilter = temp.criLineFilter > 0 ? temp.criLineFilter - 1 : temp.criLineFilter; + cri = temp.cri; + enhanceB = temp.enhanceB; + gainB = temp.gainB; + focusNumber = temp.focusNumber; + persist = temp.persist; + focus = temp.focus; + sriBypass = temp.sriBypass; + sri = temp.sri; + oti = temp.oti; + frequency = temp.frequency; + hi = temp.hi; + ffc = temp.ffc; + virtualConvex = temp.virtualConvex; + criBypass = temp.criBypass; + } +}; + +#endif //BMODESETTINGPRESETVALUES_T_H diff --git a/include/viewModel/bMode/setting/dtoInternal/BModeSettingProbePropertes.h b/include/viewModel/bMode/setting/dtoInternal/BModeSettingProbePropertes.h new file mode 100644 index 0000000..2e96263 --- /dev/null +++ b/include/viewModel/bMode/setting/dtoInternal/BModeSettingProbePropertes.h @@ -0,0 +1,44 @@ +#ifndef BMODESETTINGPROBEPROPERTES_H +#define BMODESETTINGPROBEPROPERTES_H + +#include +#include + +#include "model/ssm/dtoInternal/SsmProbeProperties.h" + +struct BModeSettingProbeProperties_t { + bool linear; + QList angleValues; + QList hiFrequencyNames; + QList piValues; + QList depthData; + + int hiFocusValuesLength; + int focusValuesLength; + int multiFocusStep; + int ffcValuesLength; + + void init(SsmProbeProperties_t temp) + { + linear = temp.linear; + + angleValues.clear(); + angleValues.append(temp.angleValues); + + hiFrequencyNames.clear(); + hiFrequencyNames.append(temp.hiNames); + + piValues.clear(); + piValues.append(temp.piValues); + + depthData.clear(); + depthData.append(temp.depthData); + + hiFocusValuesLength = temp.hiFocusValues.length(); + focusValuesLength = temp.focusValues.length(); + multiFocusStep = temp.multiFocusStep; + ffcValuesLength = temp.ffcValues[0].length(); + } +}; + +#endif //BMODESETTINGPROBEPROPERTES_H diff --git a/include/viewModel/cine/display/CineDisplayViewModel.h b/include/viewModel/cine/display/CineDisplayViewModel.h new file mode 100644 index 0000000..356dcb6 --- /dev/null +++ b/include/viewModel/cine/display/CineDisplayViewModel.h @@ -0,0 +1,26 @@ +#ifndef CINEDISPLAYVIEWMODEL_H +#define CINEDISPLAYVIEWMODEL_H + +#include "viewModel/BaseViewModel.h" + +#include "viewModel/cine/display/DataCineDisplay.h" + +class CineDisplayViewModel : public BaseViewModel +{ + Q_OBJECT + US_VIEW_MODEL(CineDisplayViewModel) + SINGLETON(CineDisplayViewModel) + +private: + DataCineDisplay_t _data; + + US_RADIO_BUTTON(cineDirection, 0) + + US_SIMPLE_BUTTON(cineForward, "", "qrc:/UI/Images/Icon/Forward.svg", true, true) + + US_SIMPLE_BUTTON(cineBackward, "", "qrc:/UI/Images/Icon/Backward.svg", true, true) + + US_SIMPLE_BUTTON(cineForwardBackward, "", "qrc:/UI/Images/Icon/ForwardBackward.svg", true, true) +}; + +#endif //CINEDISPLAYVIEWMODEL_H diff --git a/include/viewModel/cine/display/DataCineDisplay.h b/include/viewModel/cine/display/DataCineDisplay.h new file mode 100644 index 0000000..7db8725 --- /dev/null +++ b/include/viewModel/cine/display/DataCineDisplay.h @@ -0,0 +1,13 @@ +#ifndef DATACINEDISPLAY_H +#define DATACINEDISPLAY_H + +#include "model/player/type/EDirection.h" + +typedef struct DataCineDisplay_t +{ + EDirection::eDirection direction; +} DataCineDisplay_t; + +Q_DECLARE_METATYPE(DataCineDisplay_t) + +#endif //DATACINEDISPLAY_H diff --git a/include/viewModel/cine/setting/CineSettingViewModel.h b/include/viewModel/cine/setting/CineSettingViewModel.h new file mode 100644 index 0000000..d0c0330 --- /dev/null +++ b/include/viewModel/cine/setting/CineSettingViewModel.h @@ -0,0 +1,38 @@ +#ifndef CINESETTINGVIEWMODEL_H +#define CINESETTINGVIEWMODEL_H + +#include "viewModel/BaseViewModel.h" + +#include "viewModel/cine/setting/DataCineSetting.h" + +class CineSettingViewModel : public BaseViewModel +{ + Q_OBJECT + US_VIEW_MODEL(CineSettingViewModel) + SINGLETON(CineSettingViewModel) + +private: + DataCineSetting_t _data; + + US_SWITCH_BUTTON(cineRepeat, "", "", true, true, false) + + US_SWITCH_BUTTON(cinePlay, "", "", true, true, false) + + US_SWITCH_BUTTON(cineOriginalClip, "Maximize", "", true, true, false) + + US_JOYSTICK_SIMPLE(cineStart, "Start", true, true, 1) + + US_JOYSTICK_SIMPLE(cineEnd, "End", true, true, 3) + + US_SPIN_BOX(cineSpeed, "Speed", (QList({"0.5", "1", "1.5", "2"})), + "", "x", true, true, 1) + + US_JOYSTICK_SIMPLE(cineNumber, "Cine#", true, true, 2) + + US_PROPERTY(quint32, cineElapsedTime, 1) + US_PROPERTY(quint32, cineTotalTime, 2) + US_PROPERTY(quint32, cineSavedFrame, 2) + US_PROPERTY(quint32, cineTotalFrame, 4) +}; + +#endif //CINESETTINGVIEWMODEL_H diff --git a/include/viewModel/cine/setting/DataCineSetting.h b/include/viewModel/cine/setting/DataCineSetting.h new file mode 100644 index 0000000..5b69622 --- /dev/null +++ b/include/viewModel/cine/setting/DataCineSetting.h @@ -0,0 +1,20 @@ +#ifndef DATACINESETTING_H +#define DATACINESETTING_H +#include + +typedef struct DataCineSetting_t +{ + bool cineOriginalClip; + bool cineRepeat; + bool cinePlay; + bool freeze; + + int cineStart; + int cineEnd; + int cineSpeed; + int cineNumber; +} DataCineSetting_t; + +Q_DECLARE_METATYPE(DataCineSetting_t) + +#endif //DATACINESETTING_H diff --git a/include/viewModel/factory/ApplicationStarter.h b/include/viewModel/factory/ApplicationStarter.h new file mode 100644 index 0000000..7c3e610 --- /dev/null +++ b/include/viewModel/factory/ApplicationStarter.h @@ -0,0 +1,33 @@ +#ifndef APPLICATIONSTARTER_H +#define APPLICATIONSTARTER_H + +#include +#include +#include + +#include "utils/ThreadBinder.h" +#include "model/ultrasoundModule/UsEventSender.h" + +class ApplicationStarter : public QObject +{ + Q_OBJECT + US_EVENT_SENDER(private) + SINGLETON(ApplicationStarter) + +private: + QList _names; + + explicit ApplicationStarter(QObject* parent = nullptr); + + template void initModule(bool eventFilter = false); + + void hideTouchpanelMousePointer(); + char* findImseId(); + +public: + void init(); + void sendInitCommand(); + void sendStartCommand(); +}; + +#endif //APPLICATIONSTARTER_H diff --git a/include/viewModel/image/DataImage.h b/include/viewModel/image/DataImage.h new file mode 100644 index 0000000..12d84de --- /dev/null +++ b/include/viewModel/image/DataImage.h @@ -0,0 +1,21 @@ + #ifndef DATAIMAGE_H +#define DATAIMAGE_H + +#include + +typedef struct DataImage_t +{ + int sonoBNumber; + + int sonoBImageW; + int sonoBImageH; + + int sonoMImageW; + int sonoMImageH; + + bool sriB; +} DataImage_t; + +Q_DECLARE_METATYPE(DataImage_t); + +#endif //DATAIMAGE_H diff --git a/include/viewModel/image/ImageViewModel.h b/include/viewModel/image/ImageViewModel.h new file mode 100644 index 0000000..780ceec --- /dev/null +++ b/include/viewModel/image/ImageViewModel.h @@ -0,0 +1,117 @@ +#ifndef IMAGEVIEWMODEL_H +#define IMAGEVIEWMODEL_H + +#include "viewModel/BaseViewModel.h" + +#include "viewModel/image/DataImage.h" +#include "viewModel/image/dtoInternal/ImagePresetValues.h" + +#include "utils/ColorImageProvider.h" + +class ImageViewModel : public BaseViewModel +{ + Q_OBJECT + US_VIEW_MODEL(ImageViewModel) + SINGLETON(ImageViewModel) + +private: + DataImage_t _data; + + ColorImageProvider* _imageProvider; + + void applyPreset(); + ImagePresetValues_t _presetValues; + + void initialImageShow(); + void setSingleImage(); + void setDualImage(); + void setQuadImage(); + + void showImage(int totalImageNumber); + void increaseActiveImage(int totalImageNumber); + + void setImageProperty(); + void setImage1Property(); + void setImageSriProperty(); + void setImage2Property(); + void setImage3Property(); + void setImage4Property(); + + //B-Mode Image Position + US_PROPERTY_CUSTOM_SETTER(quint16, sonoBX, 0) + US_PROPERTY_CUSTOM_SETTER(quint16, sonoBY, 0) + + //B-Mode Image Size + US_PROPERTY(quint16, sonoBImageW, 0) + US_PROPERTY(quint16, sonoBImageH, 0) + + //M-Mode Image Size + US_PROPERTY(quint16, sonoMImageW, 0) + US_PROPERTY(quint16, sonoMImageH, 0) + + US_PROPERTY_CUSTOM_SETTER(QString, imageSource, "qrc:/UI/Images/SonoImage/USImageDummy.png") + + US_PROPERTY(QString, imageSriSource, "qrc:/UI/Images/SonoImage/USImageDummy.png") + + US_SWITCH_BUTTON_CUSTOM_SETTER(sriB, "B+SRI", "", true, true, false) + + US_SPIN_BOX_CUSTOM_SETTER(scale, "Scale", (QList({""})), "", "", true, true, 0) + + /*************************************************************************************************/ + /** + * View Model Parameter + */ + /**********************************************************************************************/ + + US_PROPERTY_CUSTOM_SETTER(int, activeImage, 0) + + //B-Mode Image 1 + US_IMAGE(b1Image, "", 0, 0, 0, (QList({"1"})), false, false, true, true) + + //B-Mode Image 2 + US_IMAGE(b2Image, "", 0, 0, 0, (QList({"1"})), false, false, false, true) + + //B-Mode Image 3 + US_IMAGE(b3Image, "", 0, 0, 0, (QList({"1"})), false, false, false, true) + + //B-Mode Image 4 + US_IMAGE(b4Image, "", 0, 0, 0, (QList({"1"})), false, false, false, true) + + //SRI Image + US_IMAGE(bPlusSriImage, "qrc:/UI/Images/SonoImage/USImageDummy.png", + 0, 0, 0, (QList({"1"})), false, false, true, true) + + //M-Mode Image + US_IMAGE(mImage, "qrc:/UI/Images/SonoImage/USImageDummy.png", + 0, 0, 0, (QList({"1"})), false, false, false, false) + + US_SWITCH_BUTTON(xl, "", "", true, true, false) + + US_SPIN_BOX(bMSize, "B/M", (QList({"40/60", "50/50", "60/40"})), "", "", true, true, 1) + + US_SWITCH_BUTTON(bMDirection, "", "", true, true, false) + + US_SWITCH_BUTTON_CUSTOM_SETTER(mirror, "", "qrc:/UI/Images/Icon/FlipHorizontal.svg", + true, true, false) + + US_SWITCH_BUTTON_CUSTOM_SETTER(flip, "", "qrc:/UI/Images/Icon/FlipVertical.svg", + true, true, false) + + //Image Number + US_SPIN_BOX_CUSTOM_SETTER(imageNumber, "Image #", (QList({"Single", "Dual", "Quad"})), + "", "", true, true, 0) + /* By default, UI loads B-Single view, so changing default + * value of imageNumber does not change the appearance. + */ + + US_SWITCH_BUTTON_CUSTOM_SETTER(single, "Single", "", true, true, false) + + US_SWITCH_BUTTON_CUSTOM_SETTER(dual, "Dual", "", true, true, false) + + US_SWITCH_BUTTON_CUSTOM_SETTER(quad, "Quad", "", true, true, false) + +public: + void newBipOutputImage(QVariant image); +}; + +#endif //IMAGEVIEWMODEL_H diff --git a/include/viewModel/image/dtoInternal/ImagePresetValues.h b/include/viewModel/image/dtoInternal/ImagePresetValues.h new file mode 100644 index 0000000..38ca372 --- /dev/null +++ b/include/viewModel/image/dtoInternal/ImagePresetValues.h @@ -0,0 +1,28 @@ +#ifndef IMAGEPRESETVALUES_T_H +#define IMAGEPRESETVALUES_T_H + +#include +#include + +#include "model/ssm/dtoInternal/SsmPresetValues.h" + +struct ImagePresetValues_t { + bool xl; + bool mirrorLR; + bool mirrorUD; + bool twoDSri; + int x; + int y; + + void init(SsmPresetValues_t temp) + { + xl = temp.xl; + mirrorLR = temp.mirrorLR; + mirrorUD = temp.mirrorUD; + twoDSri = temp.twoDSri; + x = temp.imageX; + y = temp.imageY; + } +}; + +#endif //IMAGEPRESETVALUES_T_H diff --git a/include/viewModel/mMode/display/DataMModeDisplay.h b/include/viewModel/mMode/display/DataMModeDisplay.h new file mode 100644 index 0000000..b863882 --- /dev/null +++ b/include/viewModel/mMode/display/DataMModeDisplay.h @@ -0,0 +1,15 @@ +#ifndef DATAMMODEDISPLAY_H +#define DATAMMODEDISPLAY_H + +#include +#include + +typedef struct DataMModeDisplay_t +{ + int tintmap; + QList graymap; +} DataMModeDisplay_t; + +Q_DECLARE_METATYPE(DataMModeDisplay_t) + +#endif // DATAMMODEDISPLAY_H diff --git a/include/viewModel/mMode/display/MModeDisplayViewModel.h b/include/viewModel/mMode/display/MModeDisplayViewModel.h new file mode 100644 index 0000000..c9ea516 --- /dev/null +++ b/include/viewModel/mMode/display/MModeDisplayViewModel.h @@ -0,0 +1,67 @@ +#ifndef MMODEDISPLAYVIEWMODEL_H +#define MMODEDISPLAYVIEWMODEL_H + +#include "viewModel/BaseViewModel.h" + +#include "viewModel/mMode/display/DataMModeDisplay.h" + +#include "model/databaseManager/type/EDatabaseRequest.h" + +class MModeDisplayViewModel : public BaseViewModel +{ + Q_OBJECT + US_VIEW_MODEL(MModeDisplayViewModel) + SINGLETON(MModeDisplayViewModel) + +private: + DataMModeDisplay_t _data; + + void nobHandle(); + + void plotByNobs(); + + void setNobs(); + + US_LIST(int, currentGrayMapData) + + //Gray Map + US_POPUP_BUTTON_CUSTOM_SETTER(grayMap, "Gray Map", + (QList({"1", "2", "3", "4", "5", "6", + "7", "8", "9", "10", "11", "12", + "13", "14", "15", "16", "17", "18", + "U1", "U2", "U3"})), + "", "", true, true, 0, true, false) + + //Tint Map + US_SPIN_BOX(tintMap, "Tint Map", + (QList({"Off", "Candle", "Sepia", "Soft Sepia", "Blue", + "Copper", "Standard", "Clear", + "Cool Blue", "Ice", "Sepia 1"})), + "", "", true, true, 0) + + US_PROPERTY(int, posX0, 0) + US_PROPERTY_CUSTOM_SETTER(int, posY0, 0) + + US_PROPERTY_CUSTOM_SETTER(int, posX1, 36) + US_PROPERTY_CUSTOM_SETTER(int, posY1, 36) + + US_PROPERTY_CUSTOM_SETTER(int, posX2, 73) + US_PROPERTY_CUSTOM_SETTER(int, posY2, 73) + + US_PROPERTY_CUSTOM_SETTER(int, posX3, 109) + US_PROPERTY_CUSTOM_SETTER(int, posY3, 109) + + US_PROPERTY_CUSTOM_SETTER(int, posX4, 146) + US_PROPERTY_CUSTOM_SETTER(int, posY4, 146) + + US_PROPERTY_CUSTOM_SETTER(int, posX5, 182) + US_PROPERTY_CUSTOM_SETTER(int, posY5, 182) + + US_PROPERTY_CUSTOM_SETTER(int, posX6, 219) + US_PROPERTY_CUSTOM_SETTER(int, posY6, 219) + + US_PROPERTY(int, posX7, 255) + US_PROPERTY_CUSTOM_SETTER(int, posY7, 255) +}; + +#endif //MMODEDISPLAYVIEWMODEL_H diff --git a/include/viewModel/mMode/setting/DataMModeSetting.h b/include/viewModel/mMode/setting/DataMModeSetting.h new file mode 100644 index 0000000..181af99 --- /dev/null +++ b/include/viewModel/mMode/setting/DataMModeSetting.h @@ -0,0 +1,9 @@ +#ifndef DATAMMODESETTING_H +#define DATAMMODESETTING_H + +struct DataMModeSetting_t +{ + int gainM; +}; + +#endif //DATAMMODESETTING_H diff --git a/include/viewModel/mMode/setting/MModeSettingViewModel.h b/include/viewModel/mMode/setting/MModeSettingViewModel.h new file mode 100644 index 0000000..75e1ddc --- /dev/null +++ b/include/viewModel/mMode/setting/MModeSettingViewModel.h @@ -0,0 +1,37 @@ +#ifndef MMODESETTINGVIEWMODEL_H +#define MMODESETTINGVIEWMODEL_H + +#include "viewModel/BaseViewModel.h" + +#include "viewModel/mMode/setting/DataMModeSetting.h" + +#include "model/databaseManager/dto/ProbeProperties/DbmProbeProperties.h" + +class MModeSettingViewModel : public BaseViewModel +{ + Q_OBJECT + US_VIEW_MODEL(MModeSettingViewModel) + SINGLETON(MModeSettingViewModel) + +private: + DataMModeSetting_t _data; + + DbmDtoProbeProperties _prbProps; + + US_SWITCH_BUTTON(mModeEnable, "M Mode", "", true, true, false) + + US_SPIN_BOX(speedM, "Speed", (QList({"0.5", "1", "1.5", "2"})), + "", "x", true, true, 1) + + US_SWITCH_BUTTON(bMQuality, "B|M Quality", "", true, true, false) + + US_SPIN_BOX(enhance, "Enhance", (QList({""})), "", "", true, true, 0) + + US_SPIN_BOX(reject, "Reject", (QList({""})), "", "", true, true, 0) + + US_SPIN_BOX(dynamicContrast, "Dy.Cnt.", (QList({""})), "", "", true, true, 0) + + US_INFO_BOX(gainM, "Gain", (QList({""})), "", "dB", true, true, 0) +}; + +#endif //MMODESETTINGVIEWMODEL_H diff --git a/include/viewModel/probe/DataProbe.h b/include/viewModel/probe/DataProbe.h new file mode 100644 index 0000000..5704175 --- /dev/null +++ b/include/viewModel/probe/DataProbe.h @@ -0,0 +1,15 @@ +#ifndef DATAPROBE_H +#define DATAPROBE_H + +#include + +typedef struct DataProbe_t +{ + int selectedProbeId; + int selectedFolderId; + int selectedPresetId; +} DataProbe_t; + +Q_DECLARE_METATYPE(DataProbe_t) + +#endif //DATAPROBE_H diff --git a/include/viewModel/probe/ProbeViewModel.h b/include/viewModel/probe/ProbeViewModel.h new file mode 100644 index 0000000..c6f71df --- /dev/null +++ b/include/viewModel/probe/ProbeViewModel.h @@ -0,0 +1,82 @@ +#ifndef PROBEVIEWMODEL_H +#define PROBEVIEWMODEL_H + +#include "viewModel/BaseViewModel.h" + +#include "viewModel/probe/DataProbe.h" + +#include "model/databaseManager/type/EDatabaseRequest.h" + +#include "viewModel/probe/dtoInternal/ProbeProbeProperties.h" +#include "viewModel/probe/dtoInternal/FolderFolderProperties.h" +#include "viewModel/probe/dtoInternal/PresetPresetProperties.h" +#include "viewModel/probe/dtoInternal/ProbeConnectedProbes.h" + +class ProbeViewModel : public BaseViewModel +{ + Q_OBJECT + US_VIEW_MODEL(ProbeViewModel) + SINGLETON(ProbeViewModel) + +private: + DataProbe_t _data; + + QList _probeList; + QList _folderList; + QList _presetList; + + QList _connectedProbes; + + void setConnectedProbes(); + void setProbes(); + void getProbes(); + void showProbes(); + void clearProbes(); + + void fetchFolders(int probeIndex); + void resetFolders(); + void getFolders(int probeId); + void showFolders(); + void clearFolders(); + + void fetchPresets(int folderIndex); + void resetPresets(); + void getPresets(int folderId); + void showPresets(); + void clearPresets(); + + US_SWITCH_BUTTON_CUSTOM_SETTER(exit, "Exit", "", true, true, false) + US_SWITCH_BUTTON_CUSTOM_SETTER(saveAndExit, "Save & Exit", "", true, true, false) + + US_PROPERTY_VIEW_ONLY(int, savedProbeIndex, 0) + US_PROPERTY_VIEW_ONLY(int, savedFolderIndex, 0) + US_PROPERTY_VIEW_ONLY(int, savedPresetIndex, 0) + + US_RADIO_BUTTON_CUSTOM_SETTER_INTERNAL(currentProbe, 0) + US_SIMPLE_BUTTON(probe0, "", "", true, true) + US_SIMPLE_BUTTON(probe1, "", "", true, true) + US_SIMPLE_BUTTON(probe2, "", "", true, true) + US_SIMPLE_BUTTON(probe3, "", "", true, true) + + US_RADIO_BUTTON_CUSTOM_SETTER_INTERNAL(currentFolder, 0) + US_SIMPLE_BUTTON(folder0, "", "", true, true) + US_SIMPLE_BUTTON(folder1, "", "", true, true) + US_SIMPLE_BUTTON(folder2, "", "", true, true) + US_SIMPLE_BUTTON(folder3, "", "", true, true) + US_SIMPLE_BUTTON(folder4, "", "", true, true) + US_SIMPLE_BUTTON(folder5, "", "", true, true) + US_SIMPLE_BUTTON(folder6, "", "", true, true) + US_SIMPLE_BUTTON(folder7, "", "", true, true) + + US_RADIO_BUTTON_INTERNAL(currentPreset, 0) + US_SIMPLE_BUTTON(preset0, "", "", true, true) + US_SIMPLE_BUTTON(preset1, "", "", true, true) + US_SIMPLE_BUTTON(preset2, "", "", true, true) + US_SIMPLE_BUTTON(preset3, "", "", true, true) + US_SIMPLE_BUTTON(preset4, "", "", true, true) + US_SIMPLE_BUTTON(preset5, "", "", true, true) + US_SIMPLE_BUTTON(preset6, "", "", true, true) + US_SIMPLE_BUTTON(preset7, "", "", true, true) +}; + +#endif //PROBEVIEWMODEL_H diff --git a/include/viewModel/probe/dtoInternal/FolderFolderProperties.h b/include/viewModel/probe/dtoInternal/FolderFolderProperties.h new file mode 100644 index 0000000..c944ec1 --- /dev/null +++ b/include/viewModel/probe/dtoInternal/FolderFolderProperties.h @@ -0,0 +1,24 @@ +#ifndef FOLDERFOLDERPROPERTIES_H +#define FOLDERFOLDERPROPERTIES_H + +#include +#include + +#include "model/databaseManager/dto/ProbeProperties/DbmApplicatoin.h" + +struct FolderFolderProperties_t { + QString image; + QString name; + int ID; + int order; + + void init(DbmDtoApplication temp) + { + image = temp.image; + name = temp.showText; + ID = temp.ID; + order = temp.orderNum; + } +}; + +#endif //FOLDERFOLDERPROPERTIES_H diff --git a/include/viewModel/probe/dtoInternal/PresetPresetProperties.h b/include/viewModel/probe/dtoInternal/PresetPresetProperties.h new file mode 100644 index 0000000..8b19afd --- /dev/null +++ b/include/viewModel/probe/dtoInternal/PresetPresetProperties.h @@ -0,0 +1,21 @@ +#ifndef PRESETPRESETPROPERTIES_H +#define PRESETPRESETPROPERTIES_H + +#include +#include + +#include "model/databaseManager/dto/ProbeProperties/DbmPreset.h" + +struct PresetPresetProperties_t { + QString name; + int ID; + int order; + void init(DbmDtoPreset temp) + { + name = temp.showText; + ID = temp.ID; + order = temp.orderNum; + } +}; + +#endif //PRESETPRESETPROPERTIES_H diff --git a/include/viewModel/probe/dtoInternal/ProbeConnectedProbes.h b/include/viewModel/probe/dtoInternal/ProbeConnectedProbes.h new file mode 100644 index 0000000..b5ce616 --- /dev/null +++ b/include/viewModel/probe/dtoInternal/ProbeConnectedProbes.h @@ -0,0 +1,19 @@ +#ifndef PROBECONNECTEDPROBES_H +#define PROBECONNECTEDPROBES_H + +#include +#include "model/ssm/dtoInternal/SsmConnectedProbe.h" + +struct ProbeConnectedProbes +{ + quint32 id; + quint32 slot; + + void init(SsmConnectedProbe_t temp) + { + id = temp.id; + slot = temp.slot; + } +}; + +#endif //PROBECONNECTEDPROBES_H diff --git a/include/viewModel/probe/dtoInternal/ProbeProbeProperties.h b/include/viewModel/probe/dtoInternal/ProbeProbeProperties.h new file mode 100644 index 0000000..9641a30 --- /dev/null +++ b/include/viewModel/probe/dtoInternal/ProbeProbeProperties.h @@ -0,0 +1,24 @@ +#ifndef PROBEPROBEPROPERTIES_H +#define PROBEPROBEPROPERTIES_H + +#include +#include + +#include "model/databaseManager/dto/ProbeProperties/DbmProbeProperties.h" + +struct ProbeProbeProperties_t { + QString image; + QString name; + bool connected; + int ID; + + void init(DbmDtoProbeProperties temp) + { + image = temp.image; + name = temp.name; + ID = temp.ID; + connected = true; + } +}; + +#endif //PROBEPROBEPROPERTIES_H diff --git a/include/viewModel/simulation/DataSimulation.h b/include/viewModel/simulation/DataSimulation.h new file mode 100644 index 0000000..4cf0dfe --- /dev/null +++ b/include/viewModel/simulation/DataSimulation.h @@ -0,0 +1,22 @@ +#ifndef DATASIMULATION_H +#define DATASIMULATION_H + +#include +#include + +typedef struct DataSimulation_t +{ + int stb; + int mla; + + bool rxTesterMode; + bool simulationTest; + bool oneshot; + bool autoIncrement; + + QString simulationFolder; +} DataSimulation_t; + +Q_DECLARE_METATYPE(DataSimulation_t); + +#endif //DATASIMULATION_H diff --git a/include/viewModel/simulation/SimulationViewModel.h b/include/viewModel/simulation/SimulationViewModel.h new file mode 100644 index 0000000..544a114 --- /dev/null +++ b/include/viewModel/simulation/SimulationViewModel.h @@ -0,0 +1,27 @@ +#ifndef SIMULATIONVIEWMODEL_H +#define SIMULATIONVIEWMODEL_H + +#include "viewModel/BaseViewModel.h" + +#include "viewModel/simulation/DataSimulation.h" + +class SimulationViewModel : public BaseViewModel +{ + Q_OBJECT + US_VIEW_MODEL(SimulationViewModel) + SINGLETON(SimulationViewModel) + +private: + DataSimulation_t _data; + + US_SWITCH_BUTTON(rxTesterMode, "Rx Tester Mode", "", true, true, true) + US_SWITCH_BUTTON(simulationTest, "Test", "", true, true, true) + US_SWITCH_BUTTON(oneshot, "One shot", "", true, true, true) + US_SWITCH_BUTTON(autoIncrement, "Auto Increment", "", true, true, true) + US_SWITCH_BUTTON(upload, "Upload", "", true, true, false) + + US_PROPERTY(QString, simulationFolder, "") + US_SIMPLE_BUTTON(workingDirOpen, "Open", "", true, true) +}; + +#endif //SIMULATIONVIEWMODEL_H diff --git a/include/viewModel/tgc/DataTgc.h b/include/viewModel/tgc/DataTgc.h new file mode 100644 index 0000000..e675da3 --- /dev/null +++ b/include/viewModel/tgc/DataTgc.h @@ -0,0 +1,14 @@ +#ifndef DATATGC_H +#define DATATGC_H + +#include +#include + +typedef struct DataTgc_t +{ + QList tgc; +} DataTgc_t; + +Q_DECLARE_METATYPE(DataTgc_t) + +#endif //DATATGC_H diff --git a/include/viewModel/tgc/TgcViewModel.h b/include/viewModel/tgc/TgcViewModel.h new file mode 100644 index 0000000..1988990 --- /dev/null +++ b/include/viewModel/tgc/TgcViewModel.h @@ -0,0 +1,73 @@ +#ifndef TGCVIEWMODEL_H +#define TGCVIEWMODEL_H + +#include "viewModel/BaseViewModel.h" + +#include "viewModel/tgc/DataTgc.h" + +#include "viewModel/tgc/dtoInternal/TgcPresetValues.h" + +class TgcViewModel : public BaseViewModel +{ + Q_OBJECT + US_VIEW_MODEL(TgcViewModel) + SINGLETON(TgcViewModel) + +private: + DataTgc_t _data; + + TgcPresetValues_t _presetValues; + + QList getTgcData(); + void saveUserTgc(int index, QList tgcData); + + void applyPreset(); + + //Default Buttons + US_PROPERTY_VIEW_ONLY(QString, tgcResetStr, "2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048") + US_PROPERTY_VIEW_ONLY(QString, tgcDefault0, "819, 819, 819, 819, 819, 819, 819, 819") + US_PROPERTY_VIEW_ONLY(QString, tgcDefault1, "2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048") + US_PROPERTY_VIEW_ONLY(QString, tgcDefault2, "3277, 3277, 3277, 3277, 3277, 3277, 3277, 3277") + US_PROPERTY_VIEW_ONLY(QString, tgcDefault3, "1229, 1433, 1638, 1843, 2048, 2253, 2458, 2662") + US_PROPERTY_VIEW_ONLY(QString, tgcDefault4, "901, 1187, 1475, 1761, 2048, 2335, 2621, 2908") + US_PROPERTY_VIEW_ONLY(QString, tgcDefault5, "410, 819, 1229, 1638, 2048, 2458, 2867, 3277") + US_PROPERTY_VIEW_ONLY(QString, tgcDefault6, "2662, 2458, 2253, 2048, 1843, 1638, 1433, 1229") + US_PROPERTY_VIEW_ONLY(QString, tgcDefault7, "2908, 2621, 2335, 2048, 1761, 1475, 1187, 901") + US_PROPERTY_VIEW_ONLY(QString, tgcDefault8, "3277, 2867, 2458, 2048, 1638, 1229, 819, 410") + + //User Buttons + US_PROPERTY(QString, tgcUser1, "819, 819, 819, 819, 819, 819, 819, 819") + US_PROPERTY(QString, tgcUser2, "2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048") + US_PROPERTY(QString, tgcUser3, "3277, 3277, 3277, 3277, 3277, 3277, 3277, 3277") + + //Slider + US_PROPERTY(float, tgc0, 2048) + US_PROPERTY(float, tgc1, 2048) + US_PROPERTY(float, tgc2, 2048) + US_PROPERTY(float, tgc3, 2048) + US_PROPERTY(float, tgc4, 2048) + US_PROPERTY(float, tgc5, 2048) + US_PROPERTY(float, tgc6, 2048) + US_PROPERTY(float, tgc7, 2048) + + //Save As + US_SIMPLE_BUTTON(tgcSaveAs, "Save As", "", true, true) + US_SIMPLE_BUTTON(tgcUserButton1, "User 1", "", true, true) + US_SIMPLE_BUTTON(tgcUserButton2, "User 2", "", true, true) + US_SIMPLE_BUTTON(tgcUserButton3, "User 3", "", true, true) + + //Reset + US_SIMPLE_BUTTON(tgcReset, "Reset", "qrc:/UI/Images/Icon/Reset.svg", true, true) + + US_PROPERTY_VIEW_ONLY(bool, enabled, true) + + //Joysticks + +//US_JOYSTICK_SIMPLE(tgcNearField, "Near Field", true, true) + +//US_JOYSTICK_SIMPLE(tgcFarField, "Far Field", true, true) + +//US_JOYSTICK_SIMPLE(tgcOveralGain, "Overal Gain", true, true) +}; + +#endif //TGCVIEWMODEL_H diff --git a/include/viewModel/tgc/dtoInternal/TgcPresetValues.h b/include/viewModel/tgc/dtoInternal/TgcPresetValues.h new file mode 100644 index 0000000..7bba2c4 --- /dev/null +++ b/include/viewModel/tgc/dtoInternal/TgcPresetValues.h @@ -0,0 +1,18 @@ +#ifndef TGCPRESETVALUES_T_H +#define TGCPRESETVALUES_T_H + +#include +#include + +#include "model/ssm/dtoInternal/SsmPresetValues.h" + +struct TgcPresetValues_t { + int tgc; + + void init(SsmPresetValues_t temp) + { + tgc = temp.tgc; + } +}; + +#endif //TGCPRESETVALUES_T_H diff --git a/include/viewModel/trackball/TrackballViewModel.h b/include/viewModel/trackball/TrackballViewModel.h new file mode 100644 index 0000000..2006409 --- /dev/null +++ b/include/viewModel/trackball/TrackballViewModel.h @@ -0,0 +1,34 @@ +#ifndef TRACKBALLVIEWMODEL_H +#define TRACKBALLVIEWMODEL_H + +#include "viewModel/BaseViewModel.h" + +class TrackballViewModel : public BaseViewModel +{ + Q_OBJECT + US_VIEW_MODEL(TrackballViewModel) + SINGLETON(TrackballViewModel) + +private: + US_TRACKBALL(centerTrackball1, "pos", true, true) + US_TRACKBALL(centerTrackball2, "center", true, false) + + US_TRACKBALL(upTrackball1, "Up 1", true, true) + US_TRACKBALL(upTrackball2, "Up 2", true, false) + + US_TRACKBALL(downTrackball1, "Down 1", true, true) + US_TRACKBALL(downTrackball2, "Down 2", true, false) + + US_TRACKBALL(rightTrackball1, "Right 1", false, false) + US_TRACKBALL(rightTrackball2, "Right 2", false, true) + + US_TRACKBALL(leftTrackball1, "Left 1", true, true) + US_TRACKBALL(leftTrackball2, "Left 2", true, false) + + US_TRACKBALL(upRightTrackball, "", true, true) + US_TRACKBALL(downRightTrackball, "", true, true) + US_TRACKBALL(upLeftTrackball, "", true, true) + US_TRACKBALL(downLeftTrackball, "", true, true) +}; + +#endif //TRACKBALLVIEWMODEL_H diff --git a/include/viewModel/user/DataUser.h b/include/viewModel/user/DataUser.h new file mode 100644 index 0000000..7862e04 --- /dev/null +++ b/include/viewModel/user/DataUser.h @@ -0,0 +1,15 @@ +#ifndef DATAUSER_H +#define DATAUSER_H + +#include + +#include "model/csm/core/EMenuTab.h" + +typedef struct DataUser_t +{ + EMenuTab::eMenuTab activeTab; +} DataUser_t; + +Q_DECLARE_METATYPE(DataUser_t); + +#endif //DATAUSER_H diff --git a/include/viewModel/user/UserViewModel.h b/include/viewModel/user/UserViewModel.h new file mode 100644 index 0000000..0331bbe --- /dev/null +++ b/include/viewModel/user/UserViewModel.h @@ -0,0 +1,24 @@ +#ifndef USERVIEWMODEL_H +#define USERVIEWMODEL_H + +#include "viewModel/BaseViewModel.h" + +#include "viewModel/user/DataUser.h" + +#include "model/csm/core/EMenuTab.h" + +class UserViewModel : public BaseViewModel +{ + Q_OBJECT + US_VIEW_MODEL(UserViewModel) + SINGLETON(UserViewModel) + +private: + DataUser_t _data; + + US_PROPERTY(EMenuTab::eMenuTab, activeTab, EMenuTab::B_TAB) + US_PROPERTY(bool, viewProbeSelection, false) + US_PROPERTY(bool, viewTGC, false) +}; + +#endif //USERVIEWMODEL_H diff --git a/include/viewModel/utils/AutoProperty.h b/include/viewModel/utils/AutoProperty.h new file mode 100644 index 0000000..e3bab77 --- /dev/null +++ b/include/viewModel/utils/AutoProperty.h @@ -0,0 +1,96 @@ +#ifndef AUTOPROPERTY_H +#define AUTOPROPERTY_H + +#include +#include "UsSimpleButton.h" +#include + +//See Gist Comment for description, usage, warnings and license information + +#define US_PROPERTY(TYPE, NAME, DEFAULT_VALUE) \ + Q_PROPERTY(TYPE NAME READ NAME WRITE NAME NOTIFY NAME ## Changed) \ +public: \ + TYPE NAME() const { return _ ## NAME; } \ + void NAME ## Internal(TYPE value) { \ + if(_ ## NAME == value)return; \ + _ ## NAME = value; \ + emit NAME ## Changed(value); \ + } \ + void NAME(TYPE value) { \ + if(_ ## NAME == value)return; \ + _ ## NAME = value; \ + emit NAME ## Changed(value); \ + send(); \ + } \ + Q_SIGNAL void NAME ## Changed(TYPE value); \ +private: \ + TYPE _ ## NAME = DEFAULT_VALUE; \ + +/*************************************************************************************************/ +#define US_PROPERTY_CUSTOM_SETTER(TYPE, NAME, DEFAULT_VALUE) \ + Q_PROPERTY(TYPE NAME READ NAME WRITE NAME NOTIFY NAME ## Changed) \ +public: \ + TYPE NAME() const { return _ ## NAME; } \ + void NAME ## Internal(TYPE value) { \ + if(_ ## NAME == value)return; \ + _ ## NAME = value; \ + emit NAME ## Changed(value); \ + } \ + void NAME(TYPE value) { \ + if(_ ## NAME == value)return; \ + _ ## NAME = value; \ + NAME ## Handle(); \ + emit NAME ## Changed(value); \ + send(); \ + } \ + Q_SIGNAL void NAME ## Changed(TYPE value); \ +private: \ + TYPE _ ## NAME = DEFAULT_VALUE; \ + void NAME ## Handle(); + +/*************************************************************************************************/ +#define US_PROPERTY_VIEW_ONLY(TYPE, NAME, DEFAULT_VALUE) \ + Q_PROPERTY(TYPE NAME READ NAME WRITE NAME NOTIFY NAME ## Changed) \ +public: \ + TYPE NAME() const { return _ ## NAME; } \ + void NAME(TYPE value) { \ + if(_ ## NAME == value)return; \ + _ ## NAME = value; \ + emit NAME ## Changed(value); \ + } \ + Q_SIGNAL void NAME ## Changed(TYPE value); \ +private: \ + TYPE _ ## NAME = DEFAULT_VALUE; \ + +/*************************************************************************************************/ +#define US_PROPERTY_INTERNAL(TYPE, NAME, DEFAULT_VALUE) \ + Q_PROPERTY(TYPE NAME READ NAME WRITE NAME NOTIFY NAME ## Changed) \ +public: \ + TYPE NAME() const { return _ ## NAME; } \ + void NAME(TYPE value) { \ + if(_ ## NAME == value)return; \ + _ ## NAME = value; \ + emit NAME ## Changed(value); \ + } \ + Q_SIGNAL void NAME ## Changed(TYPE value); \ +private: \ + TYPE _ ## NAME = DEFAULT_VALUE; \ + + +/*************************************************************************************************/ +#define US_PROPERTY_CUSTOM_SETTER_INTERNAL(TYPE, NAME, DEFAULT_VALUE) \ + Q_PROPERTY(TYPE NAME READ NAME WRITE NAME NOTIFY NAME ## Changed) \ +public: \ + TYPE NAME() const { return _ ## NAME; } \ + void NAME(TYPE value) { \ + if(_ ## NAME == value)return; \ + _ ## NAME = value; \ + NAME ## Handle(); \ + emit NAME ## Changed(value); \ + } \ + Q_SIGNAL void NAME ## Changed(TYPE value); \ +private: \ + TYPE _ ## NAME = DEFAULT_VALUE; \ + void NAME ## Handle(); + +#endif //AUTOPROPERTY_H diff --git a/include/viewModel/utils/UsImage.h b/include/viewModel/utils/UsImage.h new file mode 100644 index 0000000..532a529 --- /dev/null +++ b/include/viewModel/utils/UsImage.h @@ -0,0 +1,25 @@ +#ifndef USIMAGE_H +#define USIMAGE_H + +#endif //USIMAGE_H + +#define US_IMAGE(NAME, \ + IMAGE, \ + IMAGE_X, \ + IMAGE_Y, \ + SCALE, \ + SCALE_VALUES, \ + MIRROR, \ + FLIP, \ + ACTIVE, \ + SHOW_INDICATOR) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Source, IMAGE) \ + US_PROPERTY_VIEW_ONLY(int, NAME ## X, IMAGE_X) \ + US_PROPERTY_VIEW_ONLY(int, NAME ## Y, IMAGE_Y) \ + US_PROPERTY(int, NAME ## Scale, SCALE) \ + US_PROPERTY_VIEW_ONLY(QStringList, NAME ## ScaleValues, SCALE_VALUES) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Mirror, MIRROR) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Flip, FLIP) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Active, ACTIVE) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## ShowIndicator, SHOW_INDICATOR) \ + diff --git a/include/viewModel/utils/UsInfoBox.h b/include/viewModel/utils/UsInfoBox.h new file mode 100644 index 0000000..c6ce2bb --- /dev/null +++ b/include/viewModel/utils/UsInfoBox.h @@ -0,0 +1,50 @@ +#ifndef USINFOBOX_H +#define USINFOBOX_H + +#include "AutoProperty.h" + +#define US_INFO_BOX(NAME, \ + TITLE, \ + VALUES, \ + PREFIX, \ + SUFFIX, \ + ENABLE, \ + VISIBLE, \ + DEFAULT_VALUE) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Title, TITLE) \ + US_PROPERTY_VIEW_ONLY(QStringList, NAME ## Values, VALUES) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Prefix, PREFIX) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Suffix, SUFFIX) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Enable, ENABLE) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Visible, VISIBLE) \ + US_PROPERTY(int, NAME, DEFAULT_VALUE) \ + US_PROPERTY_VIEW_ONLY(int, NAME ## Diff, 0) + +#define US_INFO_BOX_CUSTOM_SETTER(NAME, \ + TITLE, \ + VALUES, \ + PREFIX, \ + SUFFIX, \ + ENABLE, \ + VISIBLE, \ + DEFAULT_VALUE) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Title, TITLE) \ + US_PROPERTY_VIEW_ONLY(QStringList, NAME ## Values, VALUES) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Prefix, PREFIX) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Suffix, SUFFIX) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Enable, ENABLE) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Visible, VISIBLE) \ + US_PROPERTY_CUSTOM_SETTER(int, NAME, DEFAULT_VALUE) \ + US_PROPERTY_VIEW_ONLY(int, NAME ## Diff, 0) + +#define US_INFO_BOX_BOOL(NAME, \ + TITLE, \ + ENABLE, \ + VISIBLE, \ + DEFAULT_VALUE) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Title, TITLE) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Enable, ENABLE) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Visible, VISIBLE) \ + US_PROPERTY(bool, NAME, DEFAULT_VALUE) + +#endif //USINFOBOX_H diff --git a/include/viewModel/utils/UsJoystick.h b/include/viewModel/utils/UsJoystick.h new file mode 100644 index 0000000..8ca044f --- /dev/null +++ b/include/viewModel/utils/UsJoystick.h @@ -0,0 +1,24 @@ +#ifndef USJOYSTICK_H +#define USJOYSTICK_H + +#define US_JOYSTICK_SIMPLE(NAME, \ + TITLE, \ + ENABLE, \ + VISIBLE, \ + DEFAULT_VALUE) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Title, TITLE) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Enable, ENABLE) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Visible, VISIBLE) \ + US_PROPERTY(int, NAME, DEFAULT_VALUE) + +#define US_JOYSTICK_NUMBER(NAME, \ + TITLE, \ + ENABLE, \ + VISIBLE, \ + DEFAULT_VALUE) \ + US_PROPERTY(int, NAME, DEFAULT_VALUE) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Title, TITLE) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Enable, ENABLE) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Visible, VISIBLE) + +#endif //USJOYSTICK_H diff --git a/include/viewModel/utils/UsList.h b/include/viewModel/utils/UsList.h new file mode 100644 index 0000000..483cf45 --- /dev/null +++ b/include/viewModel/utils/UsList.h @@ -0,0 +1,26 @@ +#ifndef USLIST_H +#define USLIST_H + +#include +#include + +#define US_LIST(TYPE, NAME) \ + Q_PROPERTY(QList NAME READ NAME WRITE NAME NOTIFY NAME ## Changed) \ +public: \ + QList NAME() const { return _ ## NAME; } \ + void NAME(QList value) { \ + if(_ ## NAME == value)return; \ + _ ## NAME.clear(); \ + for(int i = 0; i < value.length(); i++) \ + { \ + _ ## NAME.append(value[i]); \ + } \ + emit NAME ## Changed(value); \ + send(); \ + } \ + Q_SIGNAL void NAME ## Changed(QList value); \ +private: \ + QList _ ## NAME; \ + + +#endif //USLIST_H diff --git a/include/viewModel/utils/UsMultiButton.h b/include/viewModel/utils/UsMultiButton.h new file mode 100644 index 0000000..474418a --- /dev/null +++ b/include/viewModel/utils/UsMultiButton.h @@ -0,0 +1,50 @@ +#ifndef USMULTIBUTTON_H +#define USMULTIBUTTON_H + +#include "UsSpinBox.h" + +#define US_MULTI_BUTTON(NAME, \ + TITLE, \ + VALUES, \ + PREFIX, \ + SUFFIX, \ + ENABLE, \ + VISIBLE, \ + DEFAULT_VALUE, \ + BYPASS) \ + US_SPIN_BOX(NAME, TITLE, VALUES, PREFIX, SUFFIX, ENABLE, VISIBLE, DEFAULT_VALUE) \ + US_PROPERTY(bool, NAME ## Bypass, BYPASS) \ + +#define US_MULTI_BUTTON_CUSTOM_SETTER(NAME, \ + TITLE, \ + VALUES, \ + PREFIX, \ + SUFFIX, \ + ENABLE, \ + VISIBLE, \ + DEFAULT_VALUE, \ + BYPASS) \ + US_SPIN_BOX_CUSTOM_SETTER(NAME, \ + TITLE, \ + VALUES, \ + PREFIX, \ + SUFFIX, \ + ENABLE, \ + VISIBLE, \ + DEFAULT_VALUE) \ + US_PROPERTY_CUSTOM_SETTER(bool, NAME ## Bypass, BYPASS) \ + +#define US_MULTI_BUTTON_CUSTOM_SETTER_BYPASS_ONLY(NAME, \ + TITLE, \ + VALUES, \ + PREFIX, \ + SUFFIX, \ + ENABLE, \ + VISIBLE, \ + DEFAULT_VALUE, \ + BYPASS) \ + US_SPIN_BOX(NAME, TITLE, VALUES, PREFIX, SUFFIX, ENABLE, VISIBLE, DEFAULT_VALUE) \ + US_PROPERTY_CUSTOM_SETTER(bool, NAME ## Bypass, BYPASS) \ + + + #endif //USMULTIBUTTON_H diff --git a/include/viewModel/utils/UsRadioButton.h b/include/viewModel/utils/UsRadioButton.h new file mode 100644 index 0000000..d0626e6 --- /dev/null +++ b/include/viewModel/utils/UsRadioButton.h @@ -0,0 +1,19 @@ +#ifndef USRADIOBUTTON_H +#define USRADIOBUTTON_H + +#include "AutoProperty.h" + +#define US_RADIO_BUTTON(NAME, DEFAULT_VALUE) \ + US_PROPERTY(int, NAME, DEFAULT_VALUE) \ + +#define US_RADIO_BUTTON_CUSTOM_SETTER(NAME, DEFAULT_VALUE) \ + US_PROPERTY_CUSTOM_SETTER(int, NAME, DEFAULT_VALUE) \ + +#define US_RADIO_BUTTON_CUSTOM_SETTER_INTERNAL(NAME, DEFAULT_VALUE) \ + US_PROPERTY_CUSTOM_SETTER_INTERNAL(int, NAME, DEFAULT_VALUE) \ + +#define US_RADIO_BUTTON_INTERNAL(NAME, DEFAULT_VALUE) \ + US_PROPERTY_INTERNAL(int, NAME, DEFAULT_VALUE) \ + + +#endif //USRADIOBUTTON_H diff --git a/include/viewModel/utils/UsSimpleButton.h b/include/viewModel/utils/UsSimpleButton.h new file mode 100644 index 0000000..bc49b18 --- /dev/null +++ b/include/viewModel/utils/UsSimpleButton.h @@ -0,0 +1,37 @@ +#ifndef USSIMPLEBUTTON_H +#define USSIMPLEBUTTON_H + +#include "AutoProperty.h" + +#define US_SIMPLE_BUTTON_PROPERTY_1(NAME) US_SIMPLE_BUTTON_BASE(NAME, "fake title", "", true, true) + +#define US_SIMPLE_BUTTON_PROPERTY_2(NAME, TITLE) US_SIMPLE_BUTTON_BASE(NAME, TITLE, "", true, true) + +#define US_SIMPLE_BUTTON_PROPERTY_3(NAME, TITLE, IMAGE) \ + US_SIMPLE_BUTTON_BASE(NAME, TITLE, IMAGE, true, true) + +#define US_SIMPLE_BUTTON_PROPERTY_4(NAME, TITLE, IMAGE, ENABLE) \ + US_SIMPLE_BUTTON_BASE(NAME, TITLE, IMAGE, ENABLE, true) + +#define US_SIMPLE_BUTTON_PROPERTY_5(NAME, TITLE, IMAGE, ENABLE, VISIBLE) \ + US_SIMPLE_BUTTON_BASE(NAME, TITLE, IMAGE, ENABLE, VISIBLE) + +#define US_SIMPLE_BUTTON_ROUTER(A, B, C, D, E, FUNC, ...) FUNC + +#define US_SIMPLE_BUTTON(...) \ + US_SIMPLE_BUTTON_ROUTER(__VA_ARGS__,\ + US_SIMPLE_BUTTON_PROPERTY_5(__VA_ARGS__),\ + US_SIMPLE_BUTTON_PROPERTY_4(__VA_ARGS__),\ + US_SIMPLE_BUTTON_PROPERTY_3(__VA_ARGS__),\ + US_SIMPLE_BUTTON_PROPERTY_2(__VA_ARGS__),\ + US_SIMPLE_BUTTON_PROPERTY_1(__VA_ARGS__),\ + ) + +#define US_SIMPLE_BUTTON_BASE(NAME, TITLE, IMAGE, ENABLE, VISIBLE) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Title, TITLE) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Image, IMAGE) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Enable, ENABLE) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Visible, VISIBLE) + + +#endif // USSIMPLEBUTTON_H diff --git a/include/viewModel/utils/UsSpinBox.h b/include/viewModel/utils/UsSpinBox.h new file mode 100644 index 0000000..1b60f29 --- /dev/null +++ b/include/viewModel/utils/UsSpinBox.h @@ -0,0 +1,70 @@ +#ifndef USSPINBOX_H +#define USSPINBOX_H + +#include "AutoProperty.h" + +#define US_SPIN_BOX_SHELL(NAME, \ + TITLE, \ + VALUES, \ + PREFIX, \ + SUFFIX, \ + ENABLE, \ + VISIBLE, \ + DEFAULT_VALUE) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Title, TITLE) \ + US_PROPERTY_VIEW_ONLY(QStringList, NAME ## Values, VALUES) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Prefix, PREFIX) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Suffix, SUFFIX) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Enable, ENABLE) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Visible, VISIBLE) + +#define US_SPIN_BOX(NAME, \ + TITLE, \ + VALUES, \ + PREFIX, \ + SUFFIX, \ + ENABLE, \ + VISIBLE, \ + DEFAULT_VALUE) \ + US_SPIN_BOX_SHELL(NAME, TITLE, VALUES, PREFIX, SUFFIX, ENABLE, VISIBLE, DEFAULT_VALUE) \ + US_PROPERTY(int, NAME, DEFAULT_VALUE) + +#define US_SPIN_BOX_CUSTOM_SETTER(NAME, \ + TITLE, \ + VALUES, \ + PREFIX, \ + SUFFIX, \ + ENABLE, \ + VISIBLE, \ + DEFAULT_VALUE) \ + US_SPIN_BOX_SHELL(NAME, TITLE, VALUES, PREFIX, SUFFIX, ENABLE, VISIBLE, DEFAULT_VALUE) \ + US_PROPERTY_CUSTOM_SETTER(int, NAME, DEFAULT_VALUE) + +#define US_POPUP_BUTTON(NAME, TITLE, VALUES, PREFIX, SUFFIX, ENABLE, VISIBLE, DEFAULT_VALUE, \ + SHOW_ACTIVE_BUTTON, RESET) \ + US_SPIN_BOX(NAME, TITLE, VALUES, PREFIX, SUFFIX, ENABLE, VISIBLE, DEFAULT_VALUE) \ + US_PROPERTY_INTERNAL(bool, NAME ## ShowActiveButton, SHOW_ACTIVE_BUTTON) \ + US_PROPERTY_INTERNAL(bool, NAME ## Reset, RESET) \ + +#define US_POPUP_BUTTON_CUSTOM_SETTER(NAME, TITLE, VALUES, PREFIX, SUFFIX, ENABLE, VISIBLE, \ + DEFAULT_VALUE, SHOW_ACTIVE_BUTTON, RESET) \ + US_SPIN_BOX_CUSTOM_SETTER(NAME, TITLE, VALUES, PREFIX, SUFFIX, ENABLE, VISIBLE, DEFAULT_VALUE) \ + US_PROPERTY_INTERNAL(bool, NAME ## ShowActiveButton, SHOW_ACTIVE_BUTTON) \ + US_PROPERTY_CUSTOM_SETTER_INTERNAL(bool, NAME ## Reset, RESET) \ + +#define US_POPUP_BUTTON_CUSTOM_SETTER_CUSTOM_SHOW(NAME, \ + TITLE, \ + VALUES, \ + PREFIX, \ + SUFFIX, \ + ENABLE, \ + VISIBLE, \ + DEFAULT_VALUE, \ + SHOW_ACTIVE_BUTTON, \ + RESET) \ + US_SPIN_BOX_CUSTOM_SETTER(NAME, TITLE, VALUES, PREFIX, SUFFIX, ENABLE, VISIBLE, DEFAULT_VALUE) \ + US_PROPERTY_CUSTOM_SETTER_INTERNAL(bool, NAME ## ShowActiveButton, SHOW_ACTIVE_BUTTON) \ + US_PROPERTY_CUSTOM_SETTER_INTERNAL(bool, NAME ## Reset, RESET) \ + + +#endif //USSPINBOX_H diff --git a/include/viewModel/utils/UsSwitchButton.h b/include/viewModel/utils/UsSwitchButton.h new file mode 100644 index 0000000..1234e0a --- /dev/null +++ b/include/viewModel/utils/UsSwitchButton.h @@ -0,0 +1,15 @@ +#ifndef USSWITCHBUTTON_H +#define USSWITCHBUTTON_H + +#include "AutoProperty.h" + +#define US_SWITCH_BUTTON(NAME, TITLE, IMAGE, ENABLE, VISIBLE, DEFAULT_VALUE) \ + US_SIMPLE_BUTTON(NAME, TITLE, IMAGE, ENABLE, VISIBLE) \ + US_PROPERTY(bool, NAME, DEFAULT_VALUE) \ + +#define US_SWITCH_BUTTON_CUSTOM_SETTER(NAME, TITLE, IMAGE, ENABLE, VISIBLE, DEFAULT_VALUE) \ + US_SIMPLE_BUTTON(NAME, TITLE, IMAGE, ENABLE, VISIBLE) \ + US_PROPERTY_CUSTOM_SETTER(bool, NAME, DEFAULT_VALUE) \ + + +#endif //USSWITCHBUTTON_H diff --git a/include/viewModel/utils/UsTrackball.h b/include/viewModel/utils/UsTrackball.h new file mode 100644 index 0000000..215c22f --- /dev/null +++ b/include/viewModel/utils/UsTrackball.h @@ -0,0 +1,14 @@ +#ifndef USTRACKBALL_H +#define USTRACKBALL_H + +#include "AutoProperty.h" + +#define US_TRACKBALL(NAME, \ + TITLE, \ + ENABLE, \ + ACTIVE) \ + US_PROPERTY_VIEW_ONLY(QString, NAME ## Title, TITLE) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Enable, ENABLE) \ + US_PROPERTY_VIEW_ONLY(bool, NAME ## Active, ACTIVE) + +#endif //USTRACKBALL_H diff --git a/mainwindow.cpp b/mainwindow.cpp index 7808cb4..93520b6 100644 --- a/mainwindow.cpp +++ b/mainwindow.cpp @@ -9,7 +9,6 @@ MainWindow::MainWindow(QWidget *parent) _settings = new QSettings("Hasis", "HwTester"); _usd = new UltraSoundDevice(); - _usd->device->init(); _timeout = new QTimer(); @@ -125,6 +124,8 @@ MainWindow::MainWindow(QWidget *parent) // if(value != 0) // ui->ch_testMode->setCheckState(Qt::CheckState::Checked); + _trx.init(); + _timeout->start(1000); setReceiverConfiguration(); diff --git a/src/model/hardware/Hardware.cpp b/src/model/hardware/Hardware.cpp new file mode 100644 index 0000000..dceef78 --- /dev/null +++ b/src/model/hardware/Hardware.cpp @@ -0,0 +1,144 @@ +#include "model/hardware/Hardware.h" +#include "model/hardware/core/HwBoard.h" +#include "config/Configuration.h" +#include "model/backendImageProcessor/Bip.h" +#include "utils/Utils.h" +#include "model/bipTester/BipTester.h" +#include "model/hardware/exception/HardwareException.h" +#include "model/hardware/exception/HwExceptionDef.h" + +SINGLETON_DEF(Hardware) + +/*************************************************************************************************/ +/** + * @brief Ctor + */ +/*************************************************************************************************/ +Hardware::Hardware() : UsModule(this) +{ +} + +/*************************************************************************************************/ +/** + * @brief Dtor + */ +/*************************************************************************************************/ +Hardware::~Hardware() +{ +} + +/*************************************************************************************************/ +/** + * @brief Hook is the first hook to be called after the object has been created and moved to + * its own thread + * @details The purpose of this hook is mainly to instantiate internal children so that they are + * spawned in the target thread + * @return nething + */ +/*************************************************************************************************/ +void Hardware::afterThreadStart() +{ + _hardwareCore = new HardwareCore(); +} + +/*************************************************************************************************/ +/** + * @brief Hook is the second hook to be called after the object has been created and moved to + * its own thread + * @details The purpose of this hook is mainly to connect command and data path of the module to + * desired destinations, connection to core signals if necesserly goes here too + * @note This is prohibited to send commands in this hook, though the command itself shall receive + * its destination and be executed, but considering the fact that not all modules have their init + * called, the command chain is not necesserly complete and overall outcome may not be desired + */ +/*************************************************************************************************/ +void Hardware::init() +{ +//connect(&_hardwareCore->_hwBoard->packetEngine, +//&HardwarePacketEngine::newPacketReady, +//this, +//&Hardware::newPacketReady); + + connectDataPath(); +} + +/*************************************************************************************************/ +/** + * @brief Hook is called after inits of all \sa UsModule s has been called + * @details The purpose of this hook is mainly to start any internal + * thread and functionality if any exist, requests can work here + * @note after this hook normal life cycle begins + */ +/*************************************************************************************************/ +void Hardware::start() +{ +} + +/*************************************************************************************************/ +/** + * @brief Slot is called when packet received + * @param packet Actual packet \sa UsPacket + */ +/*************************************************************************************************/ +void Hardware::packetHandler(const UsPacket& packet) +{ +} + +/*************************************************************************************************/ +/** + * @brief This function is called when a command is issued toward this module + * @param request The Actual request \sa CommandRequest + */ +/*************************************************************************************************/ +void Hardware::commandHandler(const CommandRequest& request) +{ + switch(request.getCommandType()) + { + case ECommandType::freezeChanged: + { + auto freeze = request.getValueList()[0].value(); + try + { + if(_hardwareCore) + { +//!freeze ? _hardwareCore->_hwBoard->start() : _hardwareCore->_hwBoard->stop(); + } + } + catch(...) + { + qDebug() << "No hardware detected!"; + } + pass(request); + } + break; + + case ECommandType::bringupHardware: + try + { + _hardwareCore->startupRoutine(); + pass(request); + } + catch(HardwareException exp) + { + Logger::log(exp.getSeverityLevel(), + exp.errId(), + exp.getMessage(), + exp.getInnerMessage(), + metaObject()->className()); + + fail(request, {exp.getMessage()}); + } + break; + } +} + +/*************************************************************************************************/ +/** + * @brief Hardware::newPacketReady + * @param packet + */ +/*************************************************************************************************/ +void Hardware::newPacketReady(const UsPacket& packet) +{ + sendData(packet); +} diff --git a/src/model/hardware/core/Fan.cpp b/src/model/hardware/core/Fan.cpp new file mode 100644 index 0000000..a379b66 --- /dev/null +++ b/src/model/hardware/core/Fan.cpp @@ -0,0 +1,28 @@ +#include "model/hardware/core/Fan.h" + +Fan::Fan(QString name) +{ + _name = name; + _rpm = 0; + _lock = false; +} + +void Fan::Update() +{ + //TODO Complete this +} + +QString Fan::getName() +{ + return _name; +} + +uint32_t Fan::getRpm() +{ + return _rpm; +} + +bool Fan::isLock() +{ + return _lock; +} diff --git a/src/model/hardware/core/HardwareCore.cpp b/src/model/hardware/core/HardwareCore.cpp new file mode 100644 index 0000000..d30b697 --- /dev/null +++ b/src/model/hardware/core/HardwareCore.cpp @@ -0,0 +1,108 @@ +#include "model/hardware/core/HardwareCore.h" + +#include + +#include "model/hardware/core/PowerBoardFactory.h" +#include "model/hardware/core/TrxBoardFactory.h" +#include "model/hardware/core/RelayBoardFactory.h" +#include "model/hardware/core/HwBoard.h" +#include "logger/Logger.h" +#include "model/hardware/exception/HardwareException.h" +#include "model/hardware/exception/HwExceptionDef.h" +#include "config/Configuration.h" + +void HardwareCore::start() +{ +} + +void HardwareCore::dataReady(const QByteArray& arr) +{ + emit newData(arr); +} + +void HardwareCore::startupRoutine() +{ + checkPcieLink(); + + createTrxBoard(); + + initTrxBoard(); + + programFpga(); +} + +bool HardwareCore::hwProcFileExist() +{ + QFile file("/proc/sono_bars"); + + return file.exists(); +} + +void HardwareCore::checkPcieLink() +{ + if(!hwProcFileExist()) + { + throw HardwareException(HW_NOT_FOUND); + } + + Logger::log(ESeverityLevel::Informational, + ELogID::Info, + "PCIe link is established and driver is intact", + "Hardware"); +} + +void HardwareCore::createTrxBoard() +{ + _trxBoard = new TrxBoard(); +} + +void HardwareCore::initTrxBoard() +{ + try + { + _trxBoard->init(); + } + catch(SonoException exp) + { + throw HardwareException(TRX_INIT_FAILED, exp.what()); + } +} + +void HardwareCore::programFpga() +{ + try + { + auto path = getApplicationHomePath() + "/resource/bit/fpga.bin"; + _trxBoard->slaveFpgaProgram(path); + } + catch(SonoException exp) + { + throw HardwareException(SLAVE_PROG_FAILED, exp.what()); + } +} + +QString HardwareCore::getApplicationHomePath() +{ + return QString::fromLocal8Bit(qgetenv(US_HOME_PATH)); +} + +bool HardwareCore::selfTest() +{ +//_hwBoard->selfTest(); + + //TODO Complete compatibility check here + + return true; +} + +HardwareCore::HardwareCore() +{ +} + +HardwareCore::~HardwareCore() +{ + if(_trxBoard) + { + delete _trxBoard; + } +} diff --git a/src/model/hardware/core/HwBoard.cpp b/src/model/hardware/core/HwBoard.cpp new file mode 100644 index 0000000..8e03fd0 --- /dev/null +++ b/src/model/hardware/core/HwBoard.cpp @@ -0,0 +1,178 @@ +#include "model/hardware/core/HwBoard.h" + +#include +#include +#include + +HwBoard::HwBoard() +{ +} + +/** + * @brief Return board name + * @details The function will return the name of hardware based on hardware + * provided data + * @attention This value is a shadow value, to update it call @updateInfo() + * @return The name of board + */ +QString HwBoard::getName() +{ + return _name; +} + +/** + * @brief Return board version + * @details The function will return the version of hardware based on hardware + * provided data + * @attention This value is a shadow value, to update it call @updateInfo() + * @return The version of board + */ +QString HwBoard::getVersion() +{ + return _version; +} + +/** + * @brief PowerBoard::selfTest + * @return + */ +bool HwBoard::selfTest() +{ + //upload baby file here + + return true; +} + +bool HwBoard::updateInfo() +{ + return true; +} + +bool HwBoard::updateStatus() +{ + return true; +} + +void HwBoard::start() +{ + _run = true; + QtConcurrent::run(this, &HwBoard::readData); +} + +void HwBoard::stop() +{ + _run = false; +} + +void HwBoard::programSlave() +{ + //QFile file(path); + + //if(!file.open(QFile::ReadOnly)) + //{ + //return; + //} + + //const auto actualSize = file.size(); + //auto readSize = 0; + //while(readSize < actualSize) + //{ + //QByteArray chunk = file.read(4); + //auto value = byteArrayTo32BigEndian(chunk); + //try + //{ + //_device.device.writeWord(bar, offset, value); + //auto temp = _usd->readWord(offset + 4, bar); + //while((temp & 0x01) == 0x01) + //{ + //temp = _usd->readWord(offset + 4, bar); + //} + + //if((temp & 0x08) == 0x08) + //{ + //QString failedFpga = WhichFpgaFailed(temp); + //QString a = "init_fail flag raised, Failed FPGAs: " + failedFpga; + //throw(SonoException(a.toUtf8().data())); + //} + + //if((temp & 0x10) == 0x10) + //{ + //throw(SonoException("time_out flag raised")); + //} + //} + //catch(SonoException e) + //{ + //MESSAGE_BOX(e.what()); + + //emit updateFpgaProgressVisibility(false); + + //file.close(); + + //return; + //} + //readSize += 4; + + //auto percentage = (readSize * 100 / actualSize); + //emit updateFpgaProgressValue(percentage); + //} + + //auto temp = _usd->readWord(offset + 4, bar); + //while(((temp >> 1) & 0x03) == 0) + //{ + //temp = _usd->readWord(offset + 4, bar); + //} + + //if((temp & 0x02) == 0x02) + //{ + //MESSAGE_BOX("FPGA programming finished with success"); + //} + //else if((temp & 0x04) == 0x04) + //{ + //QString failedFpga = WhichFpgaFailed(temp); + + //MESSAGE_BOX("FPGA programming failed, Failed FPGAs: " + failedFpga); + //} + + //emit updateFpgaProgressVisibility(false); + + //file.close(); +} + +void HwBoard::readData() +{ + while(_run) + { + auto cnt = _device.getCounter(); + + if(cnt == 0) + { + std::this_thread::sleep_for(std::chrono::milliseconds(3)); + _hwCounter = 0; + continue; + } + else if(cnt != _hwCounter) + { + _hwCounter++; + + if(_hwCounter > HW_BUFFER_NUM) + { + _hwCounter = 1; + } + _device.copy(_hwCounter - 1, _swCounter); + + auto temp = QByteArray::fromRawData(_device.getBufferPtr(_swCounter), BUFFER_SIZE); + packetEngine.newData(temp); + + _swCounter++; + if(_swCounter >= SW_BUFFER_NUM) + { + _swCounter = 0; + } + } + } +} + +void HwBoard::init() +{ + _device.init(); +} diff --git a/src/model/hardware/core/IBoard.cpp b/src/model/hardware/core/IBoard.cpp new file mode 100644 index 0000000..29c35b2 --- /dev/null +++ b/src/model/hardware/core/IBoard.cpp @@ -0,0 +1 @@ +#include "model/hardware/core/IBoard.h" diff --git a/src/model/hardware/core/PowerBoard.cpp b/src/model/hardware/core/PowerBoard.cpp new file mode 100644 index 0000000..6b8072d --- /dev/null +++ b/src/model/hardware/core/PowerBoard.cpp @@ -0,0 +1,55 @@ +#include "model/hardware/core/PowerBoard.h" + +PowerBoard::PowerBoard() +{ + Status = new PowerBoardStatus(); +} + +PowerBoard::~PowerBoard() +{ + delete Status; +} + +/** + * @brief Return board name + * @details The function will return the name of hardware based on hardware + * provided data + * @attention This value is a shadow value, to update it call @updateInfo() + * @return The name of board + */ +QString PowerBoard::getName() +{ + return _name; +} + +/** + * @brief Return board version + * @details The function will return the version of hardware based on hardware + * provided data + * @attention This value is a shadow value, to update it call @updateInfo() + * @return The version of board + */ +QString PowerBoard::getVersion() +{ + return _version; +} + +/** + * @brief PowerBoard::selfTest + * @return + */ +bool PowerBoard::selfTest() +{ + return true; +} + +bool PowerBoard::updateInfo() +{ + return true; +} + +bool PowerBoard::updateStatus() +{ + return true; +} + diff --git a/src/model/hardware/core/PowerBoardFactory.cpp b/src/model/hardware/core/PowerBoardFactory.cpp new file mode 100644 index 0000000..844619c --- /dev/null +++ b/src/model/hardware/core/PowerBoardFactory.cpp @@ -0,0 +1,7 @@ +#include "model/hardware/core/PowerBoardFactory.h" +#include "model/hardware/core/PowerBoard.h" + +IBoard* PowerBoardFactory::create() +{ + return new PowerBoard(); +} diff --git a/src/model/hardware/core/PowerBoardStatus.cpp b/src/model/hardware/core/PowerBoardStatus.cpp new file mode 100644 index 0000000..250a1e4 --- /dev/null +++ b/src/model/hardware/core/PowerBoardStatus.cpp @@ -0,0 +1,15 @@ +#include "model/hardware/core/PowerBoardStatus.h" + +PowerBoardStatus::PowerBoardStatus() +{ + Voltages[0] = new Voltage("tempVolt"); + temperature = new class Temperature("tempTemp"); + fan = new class Fan("tempFan"); +} + +PowerBoardStatus::~PowerBoardStatus() +{ + delete Voltages[0]; + delete temperature; + delete fan; +} diff --git a/src/model/hardware/core/RelayBoard.cpp b/src/model/hardware/core/RelayBoard.cpp new file mode 100644 index 0000000..ee69a8e --- /dev/null +++ b/src/model/hardware/core/RelayBoard.cpp @@ -0,0 +1,32 @@ +#include "model/hardware/core/RelayBoard.h" + +RelayBoard::RelayBoard() +{ + +} + +QString RelayBoard::getName() +{ + return ""; +} + +QString RelayBoard::getVersion() +{ + return ""; +} + +bool RelayBoard::selfTest() +{ + return true; +} + +bool RelayBoard::updateInfo() +{ + return true; +} + +bool RelayBoard::updateStatus() +{ + return true; +} + diff --git a/src/model/hardware/core/RelayBoardFactory.cpp b/src/model/hardware/core/RelayBoardFactory.cpp new file mode 100644 index 0000000..ed9e7d6 --- /dev/null +++ b/src/model/hardware/core/RelayBoardFactory.cpp @@ -0,0 +1,7 @@ +#include "model/hardware/core/RelayBoardFactory.h" +#include "model/hardware/core/RelayBoard.h" + +IBoard* RelayBoardFactory::create() +{ + return new RelayBoard(); +} diff --git a/src/model/hardware/core/Temperature.cpp b/src/model/hardware/core/Temperature.cpp new file mode 100644 index 0000000..d20550e --- /dev/null +++ b/src/model/hardware/core/Temperature.cpp @@ -0,0 +1,28 @@ +#include "model/hardware/core/Temperature.h" + +Temperature::Temperature(QString name) +{ + _name = name; + _value = -100; + _status = Status::BAD; +} + +void Temperature::Update() +{ + //TODO Complete this +} + +QString Temperature::getName() +{ + return _name; +} + +float Temperature::getValue() +{ + return _value; +} + +Status Temperature::getStatus() +{ + return _status; +} diff --git a/src/model/hardware/core/TrxBoard.cpp b/src/model/hardware/core/TrxBoard.cpp index 0055b49..14d392c 100644 --- a/src/model/hardware/core/TrxBoard.cpp +++ b/src/model/hardware/core/TrxBoard.cpp @@ -1,711 +1,937 @@ #include "model/hardware/core/TrxBoard.h" -#include -#include -#include - void TrxBoard::readData() { - while(_run) - { - auto cnt = _device.getCounter(); + while(_run) + { + auto cnt = _device.getCounter(); - if(cnt == 0) - { - std::this_thread::sleep_for(std::chrono::milliseconds(3)); - _hwCounter = 0; - continue; - } - else - if(cnt != _hwCounter) - { - _hwCounter++; + if(cnt == 0) + { + std::this_thread::sleep_for(std::chrono::milliseconds(3)); + _hwCounter = 0; + continue; + } + else if(cnt != _hwCounter) + { + _hwCounter++; - _device.copy(_hwCounter - 1, _swCounter); + _device.copy(_hwCounter - 1, _swCounter); - auto temp = QByteArray::fromRawData(_device.getBufferPtr(_swCounter), BUFFER_SIZE); - //packetEngine.newData(temp); + auto temp = QByteArray::fromRawData(_device.getBufferPtr(_swCounter), BUFFER_SIZE); + packetEngine.newData(temp); - _swCounter++; - if(_swCounter >= SW_BUFFER_NUM) - { - _swCounter = 0; - } - } - } -} + emit sendFramePacket(temp); + _swCounter++; + if(_swCounter >= SW_BUFFER_NUM) + { + _swCounter = 0; + } + } + } +} void TrxBoard::scenParamsFilling(TrxBoard::eScenParams cmd) { - static quint8 scenParams = 0; - scenParams = cmd ? (scenParams+cmd) : (cmd); - if (scenParams >= TOTAL_SCEN_LUT_SRAM) - { - scenParams = TOTAL_SCEN_LUT_SRAM; - _allow = true; - } - else - _allow = false; + static quint8 scenParams = 0; + scenParams = cmd ? (scenParams + cmd) : (cmd); + if(scenParams >= TOTAL_SCEN_LUT_SRAM) + { + scenParams = TOTAL_SCEN_LUT_SRAM; + _allow = true; + } + else + { + _allow = false; + } } void TrxBoard::setSwapVector() { - _swapVec.clear(); - _swapVec << 0 << 113 << 98 << 19 << 4 << 117 << 102 << 23 << 8 << 121 << 106 << 27 << 12 << 125 << 110 << 31 << 16 << 1 << 114 << 99 - << 20 << 5 << 118 << 103 << 24 << 9 << 122 << 107 << 28 << 13 << 126 << 111 << 96 << 17 << 2 << 115 << 100 << 21 << 6 << 119 - << 104 << 25 << 10 << 123 << 108 << 29 << 14 << 127 << 112 << 97 << 18 << 3 << 116 << 101 << 22 << 7 << 120 << 105 << 26 << 11 - << 124 << 109 << 30 << 15 << 32 << 145 << 130 << 51 << 36 << 149 << 134 << 55 << 40 << 153 << 138 << 59 << 44 << 157 << 142 << 63 - << 48 << 33 << 146 << 131 << 52 << 37 << 150 << 135 << 56 << 41 << 154 << 139 << 60 << 45 << 158 << 143 << 128 << 49 << 34 << 147 - << 132 << 53 << 38 << 151 << 136 << 57 << 42 << 155 << 140 << 61 << 46 << 159 << 144 << 129 << 50 << 35 << 148 << 133 << 54 << 39 - << 152 << 137 << 58 << 43 << 156 << 141 << 62 << 47 << 64 << 177 << 162 << 83 << 68 << 181 << 166 << 87 << 72 << 185 << 170 << 91 - << 76 << 189 << 174 << 95 << 80 << 65 << 178 << 163 << 84 << 69 << 182 << 167 << 88 << 73 << 186 << 171 << 92 << 77 << 190 << 175 - << 160 << 81 << 66 << 179 << 164 << 85 << 70 << 183 << 168 << 89 << 74 << 187 << 172 << 93 << 78 << 191 << 176 << 161 << 82 << 67 - << 180 << 165 << 86 << 71 << 184 << 169 << 90 << 75 << 188 << 173 << 94 << 79; + _swapVec.clear(); + _swapVec << 0 << 113 << 98 << 19 << 4 << 117 << 102 << 23 << 8 << 121 << 106 << 27 + << 12 << 125 << 110 << 31 << 16 << 1 << 114 << 99 << 20 << 5 << 118 << 103 + << 24 << 9 << 122 << 107 << 28 << 13 << 126 << 111 << 96 << 17 << 2 << 115 + << 100 << 21 << 6 << 119 << 104 << 25 << 10 << 123 << 108 << 29 << 14 << 127 + << 112 << 97 << 18 << 3 << 116 << 101 << 22 << 7 << 120 << 105 << 26 << 11 + << 124 << 109 << 30 << 15 << 32 << 145 << 130 << 51 << 36 << 149 << 134 << 55 + << 40 << 153 << 138 << 59 << 44 << 157 << 142 << 63 << 48 << 33 << 146 << 131 + << 52 << 37 << 150 << 135 << 56 << 41 << 154 << 139 << 60 << 45 << 158 << 143 + << 128 << 49 << 34 << 147 << 132 << 53 << 38 << 151 << 136 << 57 << 42 << 155 + << 140 << 61 << 46 << 159 << 144 << 129 << 50 << 35 << 148 << 133 << 54 << 39 + << 152 << 137 << 58 << 43 << 156 << 141 << 62 << 47 << 64 << 177 << 162 << 83 + << 68 << 181 << 166 << 87 << 72 << 185 << 170 << 91 << 76 << 189 << 174 << 95 + << 80 << 65 << 178 << 163 << 84 << 69 << 182 << 167 << 88 << 73 << 186 << 171 + << 92 << 77 << 190 << 175 << 160 << 81 << 66 << 179 << 164 << 85 << 70 << 183 + << 168 << 89 << 74 << 187 << 172 << 93 << 78 << 191 << 176 << 161 << 82 << 67 + << 180 << 165 << 86 << 71 << 184 << 169 << 90 << 75 << 188 << 173 << 94 << 79; } -//QList TrxBoard::signedVector2unsignedList (QVector& sgnVec) -//{ -// _unsignedQntzrList.clear(); -//// std::list _usgnList (sgnVec.begin(), sgnVec.end()); -//// _unsignedQntzrList.fromStdList(_usgnList); -// foreach (auto i, sgnVec) -// { -// _unsignedQntzrList.push_back(static_cast(i)); -// } - -// return _unsignedQntzrList; -//} +void TrxBoard::setAfeModuleOffset() +{ + _afeModuleOffset.clear(); + _afeModuleOffset << 0x1000 << 0x2000 << 0x4000 << 8000; +} -TrxBoard::TrxBoard() : _offsetSlave0(0), _offsetSlave1(0x400000), _offsetSlave2(0x800000) +void TrxBoard::setFpgaOffset() { + _fpgaOffset.clear(); + _fpgaOffset << 0x100000 << 0x200000 << 0x300000; +} - _beamFormerSlave0 = new BeamFormer (&_device, _offsetSlave0); - _beamFormerSlave1 = new BeamFormer (&_device, _offsetSlave1); - _beamFormerSlave2 = new BeamFormer (&_device, _offsetSlave2); - _clkDistributer = new ClockDistributer(&_device); - _fpgaProgram = new FpgaProgram (&_device); - _scenPlayer = new ScenPalyer (&_device); - _bCtrlMngt = new BoardsCtrlMngt (&_device); - _bpiFlash = new BpiFlash (&_device); - _emul = new Emulator (&_device); - _misc = new Misc (&_device); - _sram = new Sram (&_device); - _dsp = new Dsp (&_device); +QList TrxBoard::floatVector2unsignedList (QVector& fVec) +{ + _unsignedQntzrList.clear(); +// std::list _usgnList (sgnVec.begin(), sgnVec.end()); +// _unsignedQntzrList.fromStdList(_usgnList); + foreach (auto i, fVec) + { + _unsignedQntzrList.push_back(static_cast(i)); + } - _adc = new AdcVoltages; - _pg = new VoltagesPg; - scenParams = new ScenGenHardwareOutput; + return _unsignedQntzrList; +} +TrxBoard::TrxBoard() : _offsetSlave0(0), _offsetSlave1(0x400000), _offsetSlave2(0x800000) +{ + _beamFormerSlave0 = new BeamFormer(&_device, _offsetSlave0); + _beamFormerSlave1 = new BeamFormer(&_device, _offsetSlave1); + _beamFormerSlave2 = new BeamFormer(&_device, _offsetSlave2); + _clkDistributer = new ClockDistributer(&_device); + _afeSlave0 = new Afe(&_device, _offsetSlave0); + _afeSlave1 = new Afe(&_device, _offsetSlave1); + _afeSlave2 = new Afe(&_device, _offsetSlave2); + _fpgaProgram = new FpgaProgram(&_device); + _scenPlayer = new ScenPalyer(&_device); + _bCtrlMngt = new BoardsCtrlMngt(&_device); + _bpiFlash = new BpiFlash(&_device); + _emul = new Emulator(&_device); + _misc = new Misc(&_device); + _sram = new Sram(&_device); + _dsp = new Dsp(&_device); + + + _adc = new AdcVoltages; + _pg = new VoltagesPg; + scenParams = new ScenGenHardwareOutput; + + _allow = false; + _run = false; setSwapVector(); - _allow = false; - - _run = true; - _device.init(); + setFpgaOffset(); + setAfeModuleOffset(); } -TrxBoard::HwRegister::HwRegister(){ - configLut = new ReceiverConfiguration; - elementPosition = new ProbeElementPosition; - rxBeamformer = new RxBeamformerProperties; - pulse = new PulseProperties; - //afe = new AfeProperties; +TrxBoard::HwRegister::HwRegister() +{ + configLut = new ReceiverConfiguration; + elementPosition = new ProbeElementPosition; + rxBeamformer = new RxBeamformerProperties; + pulse = new PulseProperties; } - TrxBoard::ScenGenHardwareOutput::ScenGenHardwareOutput() { - hwRegister = new HwRegister; - indexParams = new SramIndex; - rxParams = new SramRx; - txParams = new SramTx; + hwRegister = new HwRegister; + indexParams = new SramIndex; + rxParams = new SramRx; + txParams = new SramTx; } - TrxBoard::~TrxBoard() { - delete _beamFormerSlave0; - delete _beamFormerSlave1; - delete _beamFormerSlave2; - delete _clkDistributer; - delete _fpgaProgram; - delete _scenPlayer; - delete _bCtrlMngt; - delete _bpiFlash; - delete _emul; - delete _misc; - delete _sram; - delete _dsp; + delete _beamFormerSlave0; + delete _beamFormerSlave1; + delete _beamFormerSlave2; + delete _clkDistributer; + delete _fpgaProgram; + delete _scenPlayer; + delete _bCtrlMngt; + delete _bpiFlash; + delete _emul; + delete _misc; + delete _sram; + delete _dsp; - delete _adc; - delete _pg; - delete scenParams; + delete _adc; + delete _pg; + delete scenParams; } - -TrxBoard::HwRegister::~HwRegister(){ - delete configLut; - delete rxBeamformer; - delete elementPosition; - delete pulse; - //delete afe; +TrxBoard::HwRegister::~HwRegister() +{ + delete configLut; + delete rxBeamformer; + delete elementPosition; + delete pulse; + //delete afe; } - TrxBoard::ScenGenHardwareOutput::~ScenGenHardwareOutput() { - delete hwRegister; - delete indexParams; - delete rxParams; - delete txParams; + delete hwRegister; + delete indexParams; + delete rxParams; + delete txParams; +} + +void TrxBoard::init() +{ + this->_device.init(); + this->_bCtrlMngt->mpsInit(); + this->_bCtrlMngt->prbCtrlInit(); } void TrxBoard::setScenario(ScenGenHardwareOutput_t scenGenHw) { - scenParams->focusTypeNumber = scenGenHw.focusTypeNumber; - scenParams->totalTxShotNumber = scenGenHw.totalTxShotNumber; + scenParams->focusTypeNumber = scenGenHw.focusTypeNumber; + scenParams->totalTxShotNumber = scenGenHw.totalTxShotNumber; scenParams->rxBeamFormerNumber = scenGenHw.rxBeamFormerNumber; - scenParams->scenarioStartIndex = scenGenHw.hwRegister.scenarioStartIndex; - scenParams->scenarioEndIndex = scenGenHw.hwRegister.scenarioEndIndex; - - //scenParams->hwRegister->lpfLut = scenGenHw.hwRegister.lpfLut; - //scenParams->hwRegister->atgcLut=scenGenHw.hwRegister.atgcLut; - //scenParams->hwRegister->apodization=scenGenHw.hwRegister.apodizationLut; - scenParams->hwRegister->blendWeight=scenGenHw.hwRegister.blendWeight; - scenParams->hwRegister->elementPosition->xPosition=scenGenHw.hwRegister.elementXPosition; - scenParams->hwRegister->elementPosition->yPosition=scenGenHw.hwRegister.elementYPosition; - scenParams->hwRegister->elementPosition->zPosition=scenGenHw.hwRegister.elementZPosition; - scenParams->hwRegister->freqLut=scenGenHw.hwRegister.freqLut; - scenParams->hwRegister->dtgcLut=scenGenHw.hwRegister.dtgcLut; - scenParams->hwRegister->pulseTypeNumber=scenGenHw.hwRegister.pulseTypeNumber; - scenParams->hwRegister->rxBeamFormerTypeNumber=scenGenHw.hwRegister.rxBeamFormerTypeNumber; - scenParams->hwRegister->receiverConfigTypeNumber=scenGenHw.hwRegister.receiverConfigTypeNumber; - - scenParams->hwRegister->pulse->clear(); - foreach (auto i, scenGenHw.hwRegister.pulseProps) + scenParams->scenarioStartIndex = scenGenHw.hwRegister.scenarioStartIndex; + scenParams->scenarioEndIndex = scenGenHw.hwRegister.scenarioEndIndex; + + scenParams->hwRegister->lpfLut = scenGenHw.hwRegister.lpfLut; + scenParams->hwRegister->atgcLut=scenGenHw.hwRegister.atgcLut; + scenParams->hwRegister->apodization=scenGenHw.hwRegister.apodizationLut; + scenParams->hwRegister->blendWeight = scenGenHw.hwRegister.blendWeight; + scenParams->hwRegister->elementPosition->xPosition = scenGenHw.hwRegister.elementXPosition; + scenParams->hwRegister->elementPosition->yPosition = scenGenHw.hwRegister.elementYPosition; + scenParams->hwRegister->elementPosition->zPosition = scenGenHw.hwRegister.elementZPosition; + scenParams->hwRegister->freqLut = scenGenHw.hwRegister.freqLut; + scenParams->hwRegister->dtgcLut = scenGenHw.hwRegister.dtgcLut; + scenParams->hwRegister->pulseTypeNumber = scenGenHw.hwRegister.pulseTypeNumber; + scenParams->hwRegister->rxBeamFormerTypeNumber = scenGenHw.hwRegister.rxBeamFormerTypeNumber; + scenParams->hwRegister->receiverConfigTypeNumber = + scenGenHw.hwRegister.receiverConfigTypeNumber; + + scenParams->hwRegister->pulse->clear(); + foreach(auto i, scenGenHw.hwRegister.pulseProps) + { + scenParams->hwRegister->pulse->halfPeriod.append(i.halfPeriod); + scenParams->hwRegister->pulse->startPhase.append(i.startPhase); + scenParams->hwRegister->pulse->halfCycleNo.append(i.halfCycleNo); + scenParams->hwRegister->pulse->pulseVoltSel.append(i.pulseVoltSel); + scenParams->hwRegister->pulse->dampingPulseWidth.append(i.dampingPulseWidth); + } + + scenParams->hwRegister->rxBeamformer->clear(); + foreach(auto j, scenGenHw.hwRegister.rxBeamFormerProps) + { + scenParams->hwRegister->rxBeamformer->lag.append(j.lag); + scenParams->hwRegister->rxBeamformer->mla.append(j.mla); + scenParams->hwRegister->rxBeamformer->apodization.append(j.apodizationSel); + } + + scenParams->hwRegister->configLut->clear(); + foreach (auto k, scenGenHw.hwRegister.receiverConfigProps) { - scenParams->hwRegister->pulse->halfPeriod.append(i.halfPeriod); - scenParams->hwRegister->pulse->startPhase.append(i.startPhase); - scenParams->hwRegister->pulse->halfCycleNo.append(i.halfCycleNo); - scenParams->hwRegister->pulse->pulseVoltSel.append(i.pulseVoltSel); - scenParams->hwRegister->pulse->dampingPulseWidth.append(i.dampingPulseWidth); + scenParams->hwRegister->configLut->mla.append(k.mla); + scenParams->hwRegister->configLut->stb.append(k.stb); + scenParams->hwRegister->configLut->absEn.append(k.absEn); + scenParams->hwRegister->configLut->ddcEn.append(k.ddcEn); + scenParams->hwRegister->configLut->dpeEn.append(k.dpeEn); + scenParams->hwRegister->configLut->stbEn.append(k.stbEn); + scenParams->hwRegister->configLut->wmfEn.append(k.wmfEn); + scenParams->hwRegister->configLut->lpfSel.append(k.lpfSel); + scenParams->hwRegister->configLut->aTgcSel.append(k.aTgcSel); + scenParams->hwRegister->configLut->focusNo.append(k.focusNo); + scenParams->hwRegister->configLut->lineMode.append(k.lineMode); + scenParams->hwRegister->configLut->ncoFreqSel.append(k.ncoFreqSel); + scenParams->hwRegister->configLut->dcCancelerEn.append(k.dcCancelEn); + scenParams->hwRegister->configLut->lineFilterEn.append(k.lineFilterEn); + scenParams->hwRegister->configLut->subtractFilterEn.append(k.subtractFilterEn); } - scenParams->hwRegister->rxBeamformer->clear(); - foreach (auto j, scenGenHw.hwRegister.rxBeamFormerProps) - { - scenParams->hwRegister->rxBeamformer->lag.append(j.lag); - scenParams->hwRegister->rxBeamformer->mla.append(j.mla); - scenParams->hwRegister->rxBeamformer->apodization.append(j.apodizationSel); - } - - scenParams->hwRegister->configLut->clear(); -// foreach (auto k, scenGenHw.hwRegister.receiverConfigProps) -// { - -// } - - scenParams->indexParams->dLineNum=scenGenHw.indexParams.dLineNum; - //scenParams->indexParams->frameType=scenGenHw.indexParams. - scenParams->indexParams->dEnsembleNum=scenGenHw.indexParams.dEnsembleNum; - scenParams->indexParams->lastLineInFrame=scenGenHw.indexParams.lastLineInFrame; - scenParams->indexParams->firstLineInFrame=scenGenHw.indexParams.firstLineInFrame; - scenParams->indexParams->shotPropertiesIndex=scenGenHw.indexParams.shotPropertiesIndex; - scenParams->indexParams->pulsePropertiesIndex=scenGenHw.indexParams.pulsePropertiesIndex; - scenParams->indexParams->receiverConfigurationIndex=scenGenHw.indexParams.receiverConfigurationIndex; - - scenParams->txParams->maxDelayQ=scenGenHw.txParams.maxDelayQ; - scenParams->txParams->txFocusXPos=scenGenHw.txParams.txFocusXPos; - scenParams->txParams->txFocusYPos=scenGenHw.txParams.txFocusYPos; - scenParams->txParams->txFocusZPos=scenGenHw.txParams.txFocusZPos; - scenParams->txParams->pulseInterval=scenGenHw.pulseInterval; - scenParams->txParams->txActiveElementNumber=scenGenHw.txParams.txActiveElementNumber; - scenParams->txParams->txStartActiveElementNumber=scenGenHw.txParams.txStartActiveElementNumber; - - scenParams->rxParams->phiCos=scenGenHw.rxParams.phiCos; - scenParams->rxParams->phiSin=scenGenHw.rxParams.phiSin; - scenParams->rxParams->thetaCos=scenGenHw.rxParams.thetaCos; - scenParams->rxParams->thetaSin=scenGenHw.rxParams.thetaSin; - scenParams->rxParams->r0Position=scenGenHw.rxParams.r0Position; - scenParams->rxParams->interceptXPos=scenGenHw.rxParams.interceptXPos; - scenParams->rxParams->interceptYPos=scenGenHw.rxParams.interceptYPos; - scenParams->rxParams->interceptZPos=scenGenHw.rxParams.interceptZPos; - scenParams->rxParams->rxR0MaxDelayQ=scenGenHw.rxParams.rxR0MaxDelayQ; - scenParams->rxParams->rxR0MinDelayQ=scenGenHw.rxParams.rxR0MinDelayQ; - scenParams->rxParams->txR0MinDelayQ=scenGenHw.rxParams.txR0MinDelayQ; - scenParams->rxParams->rxFocusPointNumber=scenGenHw.rxParams.rxFocusPointNumber; - scenParams->rxParams->rxActiveElementStep=scenGenHw.rxParams.rxActiveElementStep; - scenParams->rxParams->rxR0ActiveElementNumber=scenGenHw.rxParams.rxR0ActiveElementNumber; - scenParams->rxParams->interceptPointFiringTime=scenGenHw.rxParams.interceptPointFiringTime; - scenParams->rxParams->rxR0CenterActiveElementNumber=scenGenHw.rxParams.rxR0CenterActiveElementNumber; - - - this->setScenario(scenParams); + scenParams->indexParams->dLineNum = scenGenHw.indexParams.dLineNum; + scenParams->indexParams->frameType=scenGenHw.indexParams.frameType; + scenParams->indexParams->dEnsembleNum = scenGenHw.indexParams.dEnsembleNum; + scenParams->indexParams->lastLineInFrame = scenGenHw.indexParams.lastLineInFrame; + scenParams->indexParams->firstLineInFrame = scenGenHw.indexParams.firstLineInFrame; + scenParams->indexParams->shotPropertiesIndex = scenGenHw.indexParams.shotPropertiesIndex; + scenParams->indexParams->pulsePropertiesIndex = scenGenHw.indexParams.pulsePropertiesIndex; + scenParams->indexParams->receiverConfigurationIndex = + scenGenHw.indexParams.receiverConfigurationIndex; + + scenParams->txParams->maxDelayQ = scenGenHw.txParams.maxDelayQ; + scenParams->txParams->txFocusXPos = scenGenHw.txParams.txFocusXPos; + scenParams->txParams->txFocusYPos = scenGenHw.txParams.txFocusYPos; + scenParams->txParams->txFocusZPos = scenGenHw.txParams.txFocusZPos; + scenParams->txParams->pulseInterval = scenGenHw.pulseInterval; + scenParams->txParams->txActiveElementNumber = scenGenHw.txParams.txActiveElementNumber; + scenParams->txParams->txStartActiveElementNumber = + scenGenHw.txParams.txStartActiveElementNumber; + + scenParams->rxParams->phiCos = scenGenHw.rxParams.phiCos; + scenParams->rxParams->phiSin = scenGenHw.rxParams.phiSin; + scenParams->rxParams->thetaCos = scenGenHw.rxParams.thetaCos; + scenParams->rxParams->thetaSin = scenGenHw.rxParams.thetaSin; + scenParams->rxParams->r0Position = scenGenHw.rxParams.r0Position; + scenParams->rxParams->interceptXPos = scenGenHw.rxParams.interceptXPos; + scenParams->rxParams->interceptYPos = scenGenHw.rxParams.interceptYPos; + scenParams->rxParams->interceptZPos = scenGenHw.rxParams.interceptZPos; + scenParams->rxParams->rxR0MaxDelayQ = scenGenHw.rxParams.rxR0MaxDelayQ; + scenParams->rxParams->rxR0MinDelayQ = scenGenHw.rxParams.rxR0MinDelayQ; + scenParams->rxParams->txR0MinDelayQ = scenGenHw.rxParams.txR0MinDelayQ; + scenParams->rxParams->rxFocusPointNumber = scenGenHw.rxParams.rxFocusPointNumber; + scenParams->rxParams->rxActiveElementStep = scenGenHw.rxParams.rxActiveElementStep; + scenParams->rxParams->rxR0ActiveElementNumber = scenGenHw.rxParams.rxR0ActiveElementNumber; + scenParams->rxParams->interceptPointFiringTime = scenGenHw.rxParams.interceptPointFiringTime; + scenParams->rxParams->rxR0CenterActiveElementNumber = + scenGenHw.rxParams.rxR0CenterActiveElementNumber; + + this->setScenario(scenParams); } void TrxBoard::setScenario (ScenGenHardwareOutput* scenParams) { - ///////////////////////////////// BeamFormer setting /////////////////////////////// - QList> elementPosition; - QList x; - QList y; - QList z; - - _unsignedQntzrVec.clear(); - _unsignedQntzrVec = Register::qntzr(scenParams->hwRegister->elementPosition->xPosition, 1, 18, 0, 0, true, true, true); - QList xPosQ = _unsignedQntzrVec.toList(); + ///////////////////////////////// BeamFormer setting /////////////////////////////// + QList > elementPosition; + QList x; + QList y; + QList z; + + _floatQntzrVec.clear(); + _floatQntzrVec = Calculation::qntzr(scenParams->hwRegister->elementPosition->xPosition, + 1, + 18, + 0, + 0, + true, + true, + true); + //QList xPosQ = _unsignedQntzrVec.toList(); + QList xPosQ = floatVector2unsignedList(_floatQntzrVec); + + _floatQntzrVec.clear(); + _floatQntzrVec = Calculation::qntzr(scenParams->hwRegister->elementPosition->yPosition, + 1, + 18, + 0, + 0, + true, + true, + true); + QList yPosQ = floatVector2unsignedList(_floatQntzrVec); + + _floatQntzrVec.clear(); + _floatQntzrVec = Calculation::qntzr(scenParams->hwRegister->elementPosition->zPosition, + 0, + 17, + 0, + 0, + true, + true, + true); + QList zPosQ = floatVector2unsignedList(_floatQntzrVec); + + for(quint8 i = 0; i < 3; i++) + { + for(quint8 j = 0; j < SLAVE_ELEMENT_SEGMENT; j++) + { + x.append(xPosQ.at(_swapVec.at(j + i * SLAVE_ELEMENT_SEGMENT))); + y.append(yPosQ.at(_swapVec.at(j + i * SLAVE_ELEMENT_SEGMENT))); + z.append(zPosQ.at(_swapVec.at(j + i * SLAVE_ELEMENT_SEGMENT))); + } + + elementPosition.append(x); + elementPosition.append(y); + elementPosition.append(z); + + switch(i) + { + case 0: + this->_beamFormerSlave0->probeElementPosition(elementPosition); + break; + + case 1: + this->_beamFormerSlave1->probeElementPosition(elementPosition); + break; + + case 2: + this->_beamFormerSlave2->probeElementPosition(elementPosition); + break; + } + + x.clear(); + y.clear(); + z.clear(); + elementPosition.clear(); + } + scenParamsFilling(set); + + this->_beamFormerSlave0->rxBeamformerProperties(scenParams->hwRegister->rxBeamFormerTypeNumber, + scenParams->hwRegister->rxBeamformer); + this->_beamFormerSlave1->rxBeamformerProperties(scenParams->hwRegister->rxBeamFormerTypeNumber, + scenParams->hwRegister->rxBeamformer); + this->_beamFormerSlave2->rxBeamformerProperties(scenParams->hwRegister->rxBeamFormerTypeNumber, + scenParams->hwRegister->rxBeamformer); + scenParamsFilling(set); + + this->_beamFormerSlave0->pulseProperties(scenParams->hwRegister->pulseTypeNumber, + scenParams->hwRegister->pulse); + this->_beamFormerSlave1->pulseProperties(scenParams->hwRegister->pulseTypeNumber, + scenParams->hwRegister->pulse); + this->_beamFormerSlave2->pulseProperties(scenParams->hwRegister->pulseTypeNumber, + scenParams->hwRegister->pulse); + scenParamsFilling(set); + + QList > apodizationQ; + foreach(auto vec, scenParams->hwRegister->apodization) + { + apodizationQ.push_back(vec.toList()); + } + this->_beamFormerSlave0->apodizationLut(apodizationQ); + this->_beamFormerSlave1->apodizationLut(apodizationQ); + this->_beamFormerSlave2->apodizationLut(apodizationQ); + scenParamsFilling(set); + +//this->_beamFormerSlave0->afeLut(scenParams->hwRegister->afe); +//this->_beamFormerSlave1->afeLut(scenParams->hwRegister->afe); +//this->_beamFormerSlave2->afeLut(scenParams->hwRegister->afe); +//scenParamsFilling(set); + + ///////////////////////////////// DSP setting /////////////////////////////// + this->_dsp->receiverConfigurationLut(scenParams->hwRegister->receiverConfigTypeNumber, + scenParams->hwRegister->configLut); + + _floatQntzrVec.clear(); + _floatQntzrVec = Calculation::qntzr(scenParams->hwRegister->freqLut, 0, 24, 0, 0, true); + QList freqLutQ = floatVector2unsignedList(_floatQntzrVec); + this->_dsp->frequencyLut(freqLutQ); + + _floatQntzrVec.clear(); + _floatQntzrVec = Calculation::qntzr(scenParams->hwRegister->dtgcLut, 0, 12, 8, 0, true, false); + QList dtgcLutQ = floatVector2unsignedList(_floatQntzrVec); + this->_dsp->dtgcLut(dtgcLutQ); + + QList temp; + QList > blendWeightQ; + _floatQntzrVec.clear(); + foreach(auto vec, scenParams->hwRegister->blendWeight) + { + temp.clear(); + _floatQntzrVec = Calculation::qntzr(vec, 0, 9, 8, 0, true, false, true); + temp = floatVector2unsignedList(_floatQntzrVec); + blendWeightQ.push_back(temp); + } + this->_dsp->blendWeight(blendWeightQ); + + QList > atgcLutQ; + foreach(auto vec, scenParams->hwRegister->atgcLut) + { + atgcLutQ.push_back(vec.toList()); + } + this->_dsp->atgcLut(atgcLutQ); + + QList > lpfLutQ; + foreach(auto vec, scenParams->hwRegister->lpfLut) + { + lpfLutQ.push_back(vec.toList()); + } + this->_dsp->lpfLut(lpfLutQ); + + ///////////////////////////////// Sram setting /////////////////////////////// + this->_sram->setSramIndex(scenParams->totalTxShotNumber, scenParams->indexParams); + + this->_sram->setSramTx(scenParams->focusTypeNumber, scenParams->txParams); + + this->_sram->setSramRx(scenParams->rxBeamFormerNumber, + scenParams->focusTypeNumber, + scenParams->rxParams); + + scenParamsFilling(set); + ////////////////////////////// Scen Index setting //////////////////////////// + if(scenParams->scenarioEndIndex >= scenParams->scenarioStartIndex) + { + this->_scenPlayer->setStartIndex(scenParams->scenarioStartIndex); + this->_scenPlayer->setEndIndex(scenParams->scenarioEndIndex); + } + else + { + throw SonoException( + "The scenario end index must be greater than or equal to the scenario start index"); + } +} + +void TrxBoard::setLineFilterCoefficient(QVector& lineFilterLut) +{ + _floatQntzrVec.clear(); + _floatQntzrVec = Calculation::qntzr(lineFilterLut, 0, 9, 8, 0, true, false); + QList lineFilterLutQ = floatVector2unsignedList(_floatQntzrVec); + this->_dsp->lineFilterCoefficient(lineFilterLutQ); +} + +void TrxBoard::setStbCoefficient(QVector& stbLut) +{ + QList stbLutQ = stbLut.toList(); + this->_dsp->stbCoefficient(stbLutQ); +} - _unsignedQntzrVec.clear(); - _unsignedQntzrVec = Register::qntzr(scenParams->hwRegister->elementPosition->yPosition, 1, 18, 0, 0, true, true, true); - QList yPosQ = _unsignedQntzrVec.toList(); +void TrxBoard::setAtgcMode(eAtgcMode mode, quint16 value) const +{ + this->_dsp->atgcMode(mode, value); +} - _unsignedQntzrVec.clear(); - _unsignedQntzrVec = Register::qntzr(scenParams->hwRegister->elementPosition->zPosition, 0, 17, 0, 0, true, true, true); - QList zPosQ = _unsignedQntzrVec.toList(); +void TrxBoard::setMetaData(const QByteArray metaData) const +{ + QList data; + QByteArray temp; + qint32 num; - for (quint8 i=0; i<3; i++) + while (num < metaData.size()) { - for (quint8 j=0; j_beamFormerSlave0->probeElementPosition(elementPosition); break; - case 1 : this->_beamFormerSlave1->probeElementPosition(elementPosition); break; - case 2 : this->_beamFormerSlave2->probeElementPosition(elementPosition); break; - } - - x.clear(); - y.clear(); - z.clear(); - elementPosition.clear(); + data.push_back(byteArray2UintBigEndian (temp)); + temp.clear(); + num += sizeof (quint64); } - scenParamsFilling(set); - + this->_sram->setSramMetaData(data); +} - this->_beamFormerSlave0->rxBeamformerProperties(scenParams->hwRegister->rxBeamFormerTypeNumber ,scenParams->hwRegister->rxBeamformer); - this->_beamFormerSlave1->rxBeamformerProperties(scenParams->hwRegister->rxBeamFormerTypeNumber ,scenParams->hwRegister->rxBeamformer); - this->_beamFormerSlave2->rxBeamformerProperties(scenParams->hwRegister->rxBeamFormerTypeNumber ,scenParams->hwRegister->rxBeamformer); - scenParamsFilling(set); +void TrxBoard::setDtgcLut(QVector& dtgcLut) +{ + _floatQntzrVec.clear(); + _floatQntzrVec = Calculation::qntzr(dtgcLut, 0, 12, 8, 0, true, false); + QList dtgcLutQ = floatVector2unsignedList(_floatQntzrVec); + this->_dsp->dtgcLut(dtgcLutQ); +} - this->_beamFormerSlave0->pulseProperties(scenParams->hwRegister->pulseTypeNumber ,scenParams->hwRegister->pulse); - this->_beamFormerSlave1->pulseProperties(scenParams->hwRegister->pulseTypeNumber ,scenParams->hwRegister->pulse); - this->_beamFormerSlave2->pulseProperties(scenParams->hwRegister->pulseTypeNumber ,scenParams->hwRegister->pulse); - scenParamsFilling(set); +void TrxBoard::setAfePwrdnMode(eAfePwrdnMode cmd) const +{ + this->_afeSlave0->setAfeGblPwr(cmd); + this->_afeSlave1->setAfeGblPwr(cmd); + this->_afeSlave2->setAfeGblPwr(cmd); +} +QList TrxBoard::getAfeReg(eSlaveSelect sel, quint32 afeRegAddr) +{ + QList afeRegValue; + quint32 offset(0); + afeRegValue.clear(); - QList> apodizationQ; - foreach (auto vec, scenParams->hwRegister->apodization) + switch (sel) { - apodizationQ.push_back(vec.toList()); - } - this->_beamFormerSlave0->apodizationLut(apodizationQ); - this->_beamFormerSlave1->apodizationLut(apodizationQ); - this->_beamFormerSlave2->apodizationLut(apodizationQ); - scenParamsFilling(set); + case slave0 : + this->_afeSlave0->setReadRegEnable(true); + for (quint8 i=0; i < _afeModuleOffset.size(); i++) + { + offset = (_fpgaOffset.at(slave0) + _afeModuleOffset.at(i) + afeRegAddr) * 4; + afeRegValue.push_back(this->_device.device.readWord(BAR_REG, offset)); + } + break; + case slave1 : + this->_afeSlave1->setReadRegEnable(true); + for (quint8 i=0; i < _afeModuleOffset.size(); i++) + { + offset = (_fpgaOffset.at(slave1) + _afeModuleOffset.at(i) + afeRegAddr) * 4; + afeRegValue.push_back(this->_device.device.readWord(BAR_REG, offset)); + } + break; -// this->_beamFormerSlave0->afeLut(scenParams->hwRegister->afe); -// this->_beamFormerSlave1->afeLut(scenParams->hwRegister->afe); -// this->_beamFormerSlave2->afeLut(scenParams->hwRegister->afe); -// scenParamsFilling(set); + case slave2 : + this->_afeSlave2->setReadRegEnable(true); + for (quint8 i=0; i < _afeModuleOffset.size(); i++) + { + offset = (_fpgaOffset.at(slave2) + _afeModuleOffset.at(i) + afeRegAddr) * 4; + afeRegValue.push_back(this->_device.device.readWord(BAR_REG, offset)); + } + break; + } - ///////////////////////////////// DSP setting /////////////////////////////// - this->_dsp->receiverConfigurationLut(scenParams->hwRegister->receiverConfigTypeNumber, scenParams->hwRegister->configLut); + this->_afeSlave0->setReadRegEnable(false); + this->_afeSlave1->setReadRegEnable(false); + this->_afeSlave2->setReadRegEnable(false); - _unsignedQntzrVec.clear(); - _unsignedQntzrVec = Register::qntzr(scenParams->hwRegister->freqLut, 0, 24, 0, 0, true); - QList freqLutQ = _unsignedQntzrVec.toList(); - this->_dsp->frequencyLut(freqLutQ); + return afeRegValue; +} - _unsignedQntzrVec.clear(); - _unsignedQntzrVec = Register::qntzr(scenParams->hwRegister->dtgcLut, 0, 12, 8, 0, true, false); - QList dtgcLutQ = _unsignedQntzrVec.toList(); - this->_dsp->dtgcLut(dtgcLutQ); +void TrxBoard::setAfeConfig(AfeConfig afe) +{ + this->_afeSlave0->setAfeParams(afe); + this->_afeSlave1->setAfeParams(afe); + this->_afeSlave2->setAfeParams(afe); + scenParamsFilling(set); +} - QList temp; - QList> blendWeightQ; - _unsignedQntzrVec.clear(); - foreach (auto vec, scenParams->hwRegister->blendWeight) - { - temp.clear(); - _unsignedQntzrVec = Register::qntzr(vec, 0, 9, 8, 0, true, false, true); - temp = _unsignedQntzrVec.toList(); - blendWeightQ.push_back(temp); - } - this->_dsp->blendWeight(blendWeightQ); +void TrxBoard::slaveFpgaProgram(QString path) +{ + QByteArray bitFileData; + QFile bitFile(path); + bitFileData.clear(); + if(bitFile.fileName().isEmpty()) + { + throw SonoException("No file is selected"); + } - QList> atgcLutQ; - foreach (auto vec, scenParams->hwRegister->atgcLut) - { - atgcLutQ.push_back(vec.toList()); - } - this->_dsp->atgcLut(atgcLutQ); + if(!bitFile.open(QIODevice::ReadOnly)) + { + throw SonoException("Couldn't open bit file programming"); + } + bitFileData = bitFile.readAll(); + bitFile.close(); - QList> lpfLutQ; - foreach (auto vec, scenParams->hwRegister->lpfLut) - { - lpfLutQ.push_back(vec.toList()); - } - this->_dsp->lpfLut(lpfLutQ); + this->_fpgaProgram->program(bitFileData, SLAVE_FPGA_NUMBER); + scenParamsFilling(clear); +} - ///////////////////////////////// Sram setting /////////////////////////////// - this->_sram->setSramIndex(scenParams->totalTxShotNumber, scenParams->indexParams); +void TrxBoard::setBeamFormerMode(eClkMode mode) const +{ + this->_clkDistributer->clockMode(CLOCK_DIVISION, mode); +} - this->_sram->setSramTx(scenParams->focusTypeNumber, scenParams->txParams); +void TrxBoard::scenPlayerStart(void) +{ + if(_allow) + { + this->_beamFormerSlave0->regValid(true); + this->_beamFormerSlave1->regValid(true); + this->_beamFormerSlave2->regValid(true); - this->_sram->setSramRx(scenParams->rxBeamFormerNumber, scenParams->focusTypeNumber, scenParams->rxParams); + this->_misc->setGtSendMode(BfMode); - scenParamsFilling(set); - ////////////////////////////// Scen Index setting //////////////////////////// - if (scenParams->scenarioEndIndex >= scenParams->scenarioStartIndex) - { - this->_scenPlayer->setStartIndex(scenParams->scenarioStartIndex); - this->_scenPlayer->setEndIndex(scenParams->scenarioEndIndex); - } - else - throw SonoException("The scenario end index must be greater than or equal to the scenario start index"); + this->_misc->setSyncMode(BfSyncMode); -} + this->_emul->setEmulatorDis(); + this->_device.startDma(); -void TrxBoard::setLineFilterCoefficient(QVector &lineFilterLut) -{ - _unsignedQntzrVec.clear(); - _unsignedQntzrVec = Register::qntzr(lineFilterLut, 0, 9, 8, 0, true, false); - QList lineFilterLutQ = _unsignedQntzrVec.toList(); - this->_dsp->lineFilterCoefficient(lineFilterLutQ); -} + this->_scenPlayer->control.command(true); -void TrxBoard::setStbCoefficient(QVector &stbLut) -{ - QList stbLutQ = stbLut.toList(); - this->_dsp->stbCoefficient(stbLutQ); -} + _run = true; -void TrxBoard::setAtgcMode(eAtgcMode mode, quint16 value) const -{ - this->_dsp->atgcMode(mode, value); -} + QtConcurrent::run(this, &TrxBoard::readData); + } + else + { + throw SonoException("Total scenario luts and sram parameters are not written compeletely"); + } -void TrxBoard::setDtgcLut(QVector &dtgcLut) -{ - _unsignedQntzrVec.clear(); - _unsignedQntzrVec = Register::qntzr(dtgcLut, 0, 12, 8, 0, true, false); - QList dtgcLutQ = _unsignedQntzrVec.toList(); - this->_dsp->dtgcLut(dtgcLutQ); } -void TrxBoard::setAfePwrdnMode(eAfePwrdnMode cmd) const +void TrxBoard::scenPlayerStop(void) { + _run = false; + this->_device.stopDma(); + + this->_scenPlayer->control.command(false); } -void TrxBoard::setAfeConfig(AfeProperties *afe) const -{ +//void TrxBoard::scenPlayerPause(bool pause) const +//{ +//this->_scenPlayer->control.pause(pause); +//} +void TrxBoard::emulatorInit(EmulatorProperties* config) const +{ + this->_emul->setTransferMode(config->emulOption, config->emulMode, config->transferLength); + this->_emul->setRamOffsetAddress(config->ramBufAddress); + this->_emul->setTransferRate(config->transferRate); } -void TrxBoard::slaveFpgaProgram(QString path) +void TrxBoard::emulatorStart(QString path) { - QByteArray bitFileData; - QFile bitFile(path); - bitFileData.clear(); + QByteArray sramData; + QFile emulFile(path); + sramData.clear(); - if (bitFile.fileName().isEmpty()) + if(emulFile.fileName().isEmpty()) { throw SonoException("No file is selected"); } - if (!bitFile.open(QIODevice::ReadOnly)) + if(!emulFile.open(QIODevice::ReadOnly)) { - throw SonoException("Couldn't open bit file programming"); + throw SonoException("Couldn't open frame file to emulator test"); } - bitFileData = bitFile.readAll(); - bitFile.close(); - - this->_fpgaProgram->program(bitFileData, SLAVE_FPGA_NUMBER); + sramData = emulFile.readAll(); + emulFile.close(); - scenParamsFilling(clear); -} - -void TrxBoard::setBeamFormerMode(eClkMode mode) const -{ - this->_clkDistributer->clockMode(CLOCK_DIVISION, mode); -} - - -void TrxBoard::scenPlayerStart(void) const -{ - if (_allow) + for (qint32 i = 0; i < sramData.size(); i++) { - this->_beamFormerSlave0->regValid(true); - this->_beamFormerSlave1->regValid(true); - this->_beamFormerSlave2->regValid(true); - } - else - { - throw SonoException("Total scenario luts and sram parameters are not written compeletely"); + this->_device.device.writeByte(BAR_SRAM, static_cast(i), static_cast(sramData[i])); } - this->_misc->setGtSendMode(BfMode); + this->_scenPlayer->control.command(false); - this->_misc->setSyncMode(BfSyncMode); + this->_emul->setEmulatorEn(); - this->_scenPlayer->control.command(true); -} + this->_device.startDma(); -//void TrxBoard::scenPlayerPause(bool pause) const -//{ -// this->_scenPlayer->control.pause(pause); -//} + _run = true; -void TrxBoard::scenPlayerStop(void) const -{ - this->_scenPlayer->control.command(false); + QtConcurrent::run(this, &TrxBoard::readData); } -void TrxBoard::emulatorInit(EmulatorProperties *config) const +void TrxBoard::emulatorStop() { - this->_emul->setTransferMode(config->emulOption, config->emulMode, config->transferLength); - this->_emul->setRamOffsetAddress(config->ramBufAddress); - this->_emul->setTransferRate(config->transferRate); -} + _run = false; -void TrxBoard::emulatorEnable() const -{ - this->_emul->setEmulatorEn(); -} + this->_device.stopDma(); -void TrxBoard::emulatorDisable() const -{ - this->_emul->setEmulatorDis(); + this->_emul->setEmulatorDis(); } - quint32 TrxBoard::deviceId() const { - auto pid = this->_bCtrlMngt->getPid(); - return pid; + auto pid = this->_bCtrlMngt->getPid(); + + return pid; } quint32 TrxBoard::vendorId() const { - auto vid = this->_bCtrlMngt->getVid(); - return vid; + auto vid = this->_bCtrlMngt->getVid(); + + return vid; } quint32 TrxBoard::trxId() const { - QByteArray id = this->_bCtrlMngt->trxEepromRead(EEPROM_ID_BYTE_BEGIN, EEPROM_ID_BYTE_NUMBER); - return byteArray2Uint32BigEndian(id); + QByteArray id = this->_bCtrlMngt->trxEepromRead(EEPROM_ID_BYTE_BEGIN, EEPROM_ID_BYTE_NUMBER); + + return byteArray2UintBigEndian (id); } quint32 TrxBoard::mpsId() const { - QByteArray id = this->_bCtrlMngt->mpsEepromRead(EEPROM_ID_BYTE_BEGIN, EEPROM_ID_BYTE_NUMBER); - return byteArray2Uint32BigEndian(id); + QByteArray id = this->_bCtrlMngt->mpsEepromRead(EEPROM_ID_BYTE_BEGIN, EEPROM_ID_BYTE_NUMBER); + + return byteArray2UintBigEndian (id); } quint32 TrxBoard::prbCtrlId() const { - QByteArray id = this->_bCtrlMngt->prbCtrlEepromRead(EEPROM_ID_BYTE_BEGIN, EEPROM_ID_BYTE_NUMBER); - return byteArray2Uint32BigEndian(id); + QByteArray id = + this->_bCtrlMngt->prbCtrlEepromRead(EEPROM_ID_BYTE_BEGIN, EEPROM_ID_BYTE_NUMBER); + + return byteArray2UintBigEndian (id); } quint32 TrxBoard::prbId(quint8 prbSel) const { - QByteArray id = this->_bCtrlMngt->prbEepromRead(EEPROM_ID_BYTE_BEGIN, EEPROM_ID_BYTE_NUMBER, prbSel); - return byteArray2Uint32BigEndian(id); + QByteArray id = this->_bCtrlMngt->prbEepromRead(EEPROM_ID_BYTE_BEGIN, + EEPROM_ID_BYTE_NUMBER, + prbSel); + + return byteArray2UintBigEndian (id); } void TrxBoard::getConnectedPrbId(ConnectedPrbId* prbId) const { - QVector vec; - QByteArray id; - vec.clear(); - id.clear(); - - vec = this->_bCtrlMngt->getConnectedPrb(); - - for (quint8 i=0; i < vec.size(); i++) - { - if (vec.at(i)) - id = this->_bCtrlMngt->prbEepromRead(EEPROM_ID_BYTE_BEGIN, EEPROM_ID_BYTE_NUMBER, i); - else - id.append(nullptr); - - switch (i) - { - case 0: prbId->prbA = byteArray2Uint32BigEndian(id);break; - case 1: prbId->prbB = byteArray2Uint32BigEndian(id);break; - case 2: prbId->prbC = byteArray2Uint32BigEndian(id);break; - case 3: prbId->prbD = byteArray2Uint32BigEndian(id);break; - } - - } - + QVector vec; + QByteArray id; + vec.clear(); + id.clear(); + + vec = this->_bCtrlMngt->getConnectedPrb(); + + for(quint8 i = 0; i < vec.size(); i++) + { + if(vec.at(i)) + { + id = this->_bCtrlMngt->prbEepromRead(EEPROM_ID_BYTE_BEGIN, EEPROM_ID_BYTE_NUMBER, i); + } + else + { + id.append(nullptr); + } + + switch(i) + { + case 0: + prbId->prbA = byteArray2UintBigEndian (id); + break; + + case 1: + prbId->prbB = byteArray2UintBigEndian (id); + break; + + case 2: + prbId->prbC = byteArray2UintBigEndian (id); + break; + + case 3: + prbId->prbD = byteArray2UintBigEndian (id); + break; + } + } } QString TrxBoard::trxInfo() const { - QString str = QString(this->_bCtrlMngt->trxEepromRead(EEPROM_INFO_BYTE_BEGIN, EEPROM_INFO_BYTE_NUMBER)); - return str; + QString str = + QString(this->_bCtrlMngt->trxEepromRead(EEPROM_INFO_BYTE_BEGIN, EEPROM_INFO_BYTE_NUMBER)); + + return str; } QString TrxBoard::mpsInfo() const { - QString str = QString(this->_bCtrlMngt->mpsEepromRead(EEPROM_INFO_BYTE_BEGIN, EEPROM_INFO_BYTE_NUMBER)); - return str; + QString str = + QString(this->_bCtrlMngt->mpsEepromRead(EEPROM_INFO_BYTE_BEGIN, EEPROM_INFO_BYTE_NUMBER)); + + return str; } QString TrxBoard::prbCtrlInfo() const { - QString str = QString(this->_bCtrlMngt->prbCtrlEepromRead(EEPROM_INFO_BYTE_BEGIN, EEPROM_INFO_BYTE_NUMBER)); - return str; + QString str = + QString(this->_bCtrlMngt->prbCtrlEepromRead(EEPROM_INFO_BYTE_BEGIN, + EEPROM_INFO_BYTE_NUMBER)); + + return str; } QByteArray TrxBoard::prbInfo(quint8 prbSel) const { - return this->_bCtrlMngt->prbEepromRead(EEPROM_INFO_BYTE_BEGIN, EEPROM_INFO_BYTE_NUMBER, prbSel); + return this->_bCtrlMngt->prbEepromRead(EEPROM_INFO_BYTE_BEGIN, EEPROM_INFO_BYTE_NUMBER, prbSel); } void TrxBoard::getConnectedPrbInfo(ConnectedPrbInfo* prbInfo) const { - QByteArray info; - QVector vec; - info.clear(); - vec.clear(); + QByteArray info; + QVector vec; + info.clear(); + vec.clear(); - vec = this->_bCtrlMngt->getConnectedPrb(); + vec = this->_bCtrlMngt->getConnectedPrb(); - for (quint8 i=0; i < vec.size(); i++) - { - if (vec.at(i)) - info = this->_bCtrlMngt->prbEepromRead(EEPROM_INFO_BYTE_BEGIN, EEPROM_INFO_BYTE_NUMBER, i); - else - info.append(nullptr); + for(quint8 i = 0; i < vec.size(); i++) + { + if(vec.at(i)) + { + info = this->_bCtrlMngt->prbEepromRead(EEPROM_INFO_BYTE_BEGIN, + EEPROM_INFO_BYTE_NUMBER, + i); + } + else + { + info.append(nullptr); + } - switch (i) - { - case 0: prbInfo->prbA = info;break; - case 1: prbInfo->prbB = info;break; - case 2: prbInfo->prbC = info;break; - case 3: prbInfo->prbD = info;break; - } + switch(i) + { + case 0: + prbInfo->prbA = info; + break; - } + case 1: + prbInfo->prbB = info; + break; -} + case 2: + prbInfo->prbC = info; + break; + case 3: + prbInfo->prbD = info; + break; + } + } +} -void TrxBoard::supervisorRbValue(SupervisorRbValue *sValue) const +void TrxBoard::supervisorRbValue(SupervisorRbValue* sValue) const { - this->_bCtrlMngt->getSupervisorValue(sValue); + this->_bCtrlMngt->getSupervisorValue(sValue); } -void TrxBoard::mpsFaultStatus(MpsFaultStatus *faultStatus) const +void TrxBoard::mpsFaultStatus(MpsFaultStatus* faultStatus) const { - this->_bCtrlMngt->getMpsFault(faultStatus); + this->_bCtrlMngt->getMpsFault(faultStatus); } void TrxBoard::mpsReset() const { - this->_bCtrlMngt->setMpsReset(); + this->_bCtrlMngt->setMpsReset(); } void TrxBoard::mpsSetAo(float voltA, float voltB) const { - this->_bCtrlMngt->mpsHvSet(voltA, voltB); + this->_bCtrlMngt->mpsHvSet(voltA, voltB); } - void TrxBoard::selectProbe(eSelectProbe prbSel) const { - this->_bCtrlMngt->setProbeSelect(prbSel); + this->_bCtrlMngt->setProbeSelect(prbSel); } void TrxBoard::getHealthStatus(HealthStatus* healStat) const { -// healStat->criticalComponentTemperature = this->_bCtrlMngt->getTrxFpgaTemp(); - healStat->systemTemperature = this->_bCtrlMngt->getTrxTempSensor(); - this->_bCtrlMngt->getTrxBoardVoltages(_adc, _pg); - this->_bCtrlMngt->getTrxVoltagesPg(_pg); - healStat->adcMon = _adc; - healStat->voltsPg = _pg; +//healStat->criticalComponentTemperature = this->_bCtrlMngt->getTrxFpgaTemp(); + healStat->systemTemperature = this->_bCtrlMngt->getTrxTempSensor(); + this->_bCtrlMngt->getTrxBoardVoltages(_adc, _pg); + this->_bCtrlMngt->getTrxVoltagesPg(_pg); + healStat->adcMon = _adc; + healStat->voltsPg = _pg; } -void TrxBoard::init() const -{ - this->_bCtrlMngt->mpsInit(); - this->_bCtrlMngt->prbCtrlInit(); -} - - - void TrxBoard::mcsProgram(QString path) { - QFile mcsFile(path); - - if (mcsFile.fileName().isEmpty()) - throw SonoException("No file is selected"); + QFile mcsFile(path); - if (!mcsFile.open(QIODevice::ReadOnly)) - throw SonoException("Couldn't open mcs file programming"); + if(mcsFile.fileName().isEmpty()) + { + throw SonoException("No file is selected"); + } + if(!mcsFile.open(QIODevice::ReadOnly)) + { + throw SonoException("Couldn't open mcs file programming"); + } - QByteArray mcsFileData = mcsFile.readAll(); - this->_bpiFlash->writeMcs(mcsFileData); + QByteArray mcsFileData = mcsFile.readAll(); + this->_bpiFlash->writeMcs(mcsFileData); - mcsFileData.clear(); - mcsFile.close(); + mcsFileData.clear(); + mcsFile.close(); - scenParamsFilling(clear); + scenParamsFilling(clear); } void TrxBoard::mcsVerify(QString path) const { - QFile mcsFile(path); + QFile mcsFile(path); - if (mcsFile.fileName().isEmpty()) - throw SonoException("No file is selected"); + if(mcsFile.fileName().isEmpty()) + { + throw SonoException("No file is selected"); + } - if (!mcsFile.open(QIODevice::WriteOnly)) - throw SonoException("Couldn't open mcs file programming"); + if(!mcsFile.open(QIODevice::WriteOnly)) + { + throw SonoException("Couldn't open mcs file programming"); + } - QTextStream save(&mcsFile); + QTextStream save(&mcsFile); - (*_mcsList).clear(); - this->_bpiFlash->readMcs(_mcsList); + (*_mcsList).clear(); + this->_bpiFlash->readMcs(_mcsList); - for (auto i=0; i < MCS_FILE_SIZE; i++) - { - save << (*_mcsList).at(i); - } - mcsFile.flush(); - mcsFile.close(); + for(auto i = 0; i < MCS_FILE_SIZE; i++) + { + save << (*_mcsList).at(i); + } + mcsFile.flush(); + mcsFile.close(); } -void TrxBoard::getTrxStatus(StatusVec *status) const +void TrxBoard::getTrxStatus(StatusVec* status) const { - this->_misc->getStatusVector(status); + this->_misc->getStatusVector(status); } -void TrxBoard::getFpgasCodeVersion(FpgaCodeVersion *version) const +void TrxBoard::getFpgasCodeVersion(FpgaCodeVersion* version) const { - this->_misc->getFpgaVersion(version); + this->_misc->getFpgaVersion(version); } - - diff --git a/src/model/hardware/core/TrxBoardFactory.cpp b/src/model/hardware/core/TrxBoardFactory.cpp new file mode 100644 index 0000000..c1d49ad --- /dev/null +++ b/src/model/hardware/core/TrxBoardFactory.cpp @@ -0,0 +1,7 @@ +#include "model/hardware/core/TrxBoardFactory.h" +#include "model/hardware/core/HwBoard.h" + +IBoard* TrxBoardFactory::create() +{ + return Q_NULLPTR;//new TrxBoard(); +} diff --git a/src/model/hardware/core/Voltage.cpp b/src/model/hardware/core/Voltage.cpp new file mode 100644 index 0000000..7e4cb79 --- /dev/null +++ b/src/model/hardware/core/Voltage.cpp @@ -0,0 +1,35 @@ +#include "model/hardware/core/Voltage.h" + +Voltage::Voltage(QString name) +{ + _name = name; + _value = -100; + _current = -100; + _status = Status::BAD; +} + +void Voltage::Update() +{ + //TODO complete +} + +QString Voltage::getName() +{ + return _name; +} + +float Voltage::getValue() +{ + return _value; +} + +float Voltage::getCurrent() +{ + return _current; +} + +Status Voltage::getStatus() +{ + return _status; +} + diff --git a/src/model/hardware/core/register/Field.cpp b/src/model/hardware/core/register/Field.cpp index b46fc5a..068958f 100644 --- a/src/model/hardware/core/register/Field.cpp +++ b/src/model/hardware/core/register/Field.cpp @@ -7,19 +7,20 @@ Field::Field(quint32 mask, bool isSigned) findPosition(); findLength(); - findZeroBasedMask(); + findZeroBasedMask(); } +/*************************************************************************************************/ Field::Field(quint64 maskLong) { - _maskLong = maskLong; + _maskLong = maskLong; - findPositionLong(); - findLengthLong(); - findZeroBasedMaskLong(); + findPositionLong(); + findLengthLong(); + findZeroBasedMaskLong(); } - +/*************************************************************************************************/ void Field::findLength() { auto temp = _mask >> _position; @@ -29,21 +30,23 @@ void Field::findLength() { temp = temp >> 1; _length++; - } + } } +/*************************************************************************************************/ void Field::findLengthLong() { - auto temp = _maskLong >> _position; + auto temp = _maskLong >> _position; - _length = 0; - while((temp & 0x1) == 0x1) - { - temp = temp >> 1; - _length++; - } + _length = 0; + while((temp & 0x1) == 0x1) + { + temp = temp >> 1; + _length++; + } } +/*************************************************************************************************/ void Field::findPosition() { @@ -53,40 +56,42 @@ void Field::findPosition() { temp = temp >> 1; _position++; - } + } } +/*************************************************************************************************/ void Field::findPositionLong() { - auto temp = _maskLong; - _position = 0; - while((temp & 0x1) != 0x1) - { - temp = temp >> 1; - _position++; - } + auto temp = _maskLong; + _position = 0; + while((temp & 0x1) != 0x1) + { + temp = temp >> 1; + _position++; + } } - +/*************************************************************************************************/ void Field::findZeroBasedMask() { _zeroBasedMask = 0; for(auto i = 0; i < _length; i++) { _zeroBasedMask |= (1 << i); - } + } } +/*************************************************************************************************/ void Field::findZeroBasedMaskLong() { - _zeroBasedMaskLong = 0; - for(auto i = 0; i < _length; i++) - { - _zeroBasedMaskLong |= (1 << i); - } + _zeroBasedMaskLong = 0; + for(auto i = 0; i < _length; i++) + { + _zeroBasedMaskLong |= (1 << i); + } } - +/*************************************************************************************************/ Field* Field::fromBitPosition(quint32 bitPosition) { auto mask = 1U << bitPosition; @@ -94,27 +99,31 @@ Field* Field::fromBitPosition(quint32 bitPosition) return new Field(mask, false); } +/*************************************************************************************************/ Field* Field::fromMaskSigned(quint32 mask) { return new Field(mask, true); } +/*************************************************************************************************/ Field* Field::fromMaskUnsigned(quint32 mask) { - return new Field(mask, false); + return new Field(mask, false); } -Field *Field::fromMaskUnsignedLong(quint64 mask) +/*************************************************************************************************/ +Field* Field::fromMaskUnsignedLong(quint64 mask) { - return new Field(mask); + return new Field(mask); } - +/*************************************************************************************************/ quint32 Field::getValue() { - return _value; + return _value; } +/*************************************************************************************************/ bool Field::isUpdated() { auto temp = _isUpdated; @@ -123,6 +132,7 @@ bool Field::isUpdated() return temp; } +/*************************************************************************************************/ void Field::setValue(quint32 value) { if(_value == value) @@ -131,20 +141,22 @@ void Field::setValue(quint32 value) } _value = value; - _isUpdated = true; + _isUpdated = true; } +/*************************************************************************************************/ void Field::setValueLong(quint64 valueLong) { - if(_valueLong == valueLong) - { - return; - } + if(_valueLong == valueLong) + { + return; + } - _valueLong = valueLong; - _isUpdated = true; + _valueLong = valueLong; + _isUpdated = true; } +/*************************************************************************************************/ void Field::updateValue(quint32 value) { value = value >> _position; @@ -158,21 +170,22 @@ void Field::updateValue(quint32 value) _value = value; } - +/*************************************************************************************************/ quint32 Field::getRegisterWriteValue() { auto value = _value & _zeroBasedMask; value = value << _position; value &= _mask; - return value; + return value; } +/*************************************************************************************************/ quint64 Field::getRegisterWriteValueLong() { - auto valueLong = _valueLong & _zeroBasedMaskLong; - valueLong = valueLong << _position; - valueLong &= _maskLong; + auto valueLong = _valueLong & _zeroBasedMaskLong; + valueLong = valueLong << _position; + valueLong &= _maskLong; - return valueLong; + return valueLong; } diff --git a/src/model/hardware/core/register/Register.cpp b/src/model/hardware/core/register/Register.cpp index 093b566..d0e64ff 100644 --- a/src/model/hardware/core/register/Register.cpp +++ b/src/model/hardware/core/register/Register.cpp @@ -1,13 +1,14 @@ #include "model/hardware/core/register/Register.h" -Register::Register(quint8 bar, quint32 offset, SonoDevice *device, quint32 arrayLength) +Register::Register(quint8 bar, quint32 offset, SonoDevice* device, quint32 arrayLength) { - _bar = bar; - _offset = offset; - _arrayLength = arrayLength; - _device = device; + _bar = bar; + _offset = offset; + _arrayLength = arrayLength; + _device = device; } +/*************************************************************************************************/ Register::~Register() { for(auto i = 0; i < _fields.length(); i++) @@ -17,11 +18,13 @@ Register::~Register() _fields.clear(); } +/*************************************************************************************************/ quint32 Register::getValue() { return _value; } +/*************************************************************************************************/ void Register::setValue(quint32 value) { if(_value == value) @@ -30,19 +33,22 @@ void Register::setValue(quint32 value) } _value = value; - _isUpdated = true; + _isUpdated = true; } +/*************************************************************************************************/ void Register::changeOffset(quint32 offset) { - _offset = offset; + _offset = offset; } +/*************************************************************************************************/ quint32 Register::getCurrentOffset() const { - return _offset; + return _offset; } +/*************************************************************************************************/ bool Register::isUpdated() { auto temp = _isUpdated; @@ -51,192 +57,94 @@ bool Register::isUpdated() return temp; } - -void Register::update() //update single register +/*************************************************************************************************/ +void Register::update() { - quint32 value = 0; - for(auto i = 0; i < _fields.length(); i++) - { - value |= _fields[i]->getRegisterWriteValue(); - } + quint32 value = 0; + for(auto i = 0; i < _fields.length(); i++) + { + value |= _fields[i]->getRegisterWriteValue(); + } - _device->device.writeWord(_bar, _offset, value); + _device->device.writeWord(_bar, _offset, value); } -void Register::updateLong() //update single register for Long Value +/*************************************************************************************************/ +void Register::updateLong() { - quint64 value = 0; - for(auto i = 0; i < _fields.length(); i++) - { - value |= _fields[i]->getRegisterWriteValueLong(); - } + quint64 value = 0; + for(auto i = 0; i < _fields.length(); i++) + { + value |= _fields[i]->getRegisterWriteValueLong(); + } - _device->device.writeLong(_bar, _offset, value); + _device->device.writeLong(_bar, _offset, value); } - +/*************************************************************************************************/ void Register::updateArray(bool isVariable, quint8 arrayLength) //update array register { - quint32 value; + quint32 value; - if (isVariable) - _arrayLength = arrayLength; + if(isVariable) + { + _arrayLength = arrayLength; + } - for(quint32 i = 0; i < _arrayLength; i++) - { - prepareData(i); + for(quint32 i = 0; i < _arrayLength; i++) + { + prepareData(i); - value = 0; - for(auto j = 0; j < _fields.length(); j++) - { - value |= _fields[j]->getRegisterWriteValue(); - } + value = 0; + for(auto j = 0; j < _fields.length(); j++) + { + value |= _fields[j]->getRegisterWriteValue(); + } - _device->device.writeWord(_bar, _offset + i*4, value); - } + _device->device.writeWord(_bar, _offset + i * 4, value); + } } -void Register::updateArrayLong(quint8 interval, quint32 arrayLength) //update array register for Long Value +/*************************************************************************************************/ +void Register::updateArrayLong(quint8 interval, quint32 arrayLength) { - quint64 value; + quint64 value; - for(quint32 i = 0; i < arrayLength; i++) - { - prepareData(i); + for(quint32 i = 0; i < arrayLength; i++) + { + prepareData(i); - value = 0; - for(auto j = 0; j < _fields.length(); j++) - { - value |= _fields[j]->getRegisterWriteValueLong(); - } + value = 0; + for(auto j = 0; j < _fields.length(); j++) + { + value |= _fields[j]->getRegisterWriteValueLong(); + } - _device->device.writeLong(_bar, _offset + interval*i*8, value); - } + _device->device.writeLong(_bar, _offset + interval * i * 8, value); + } } - +/*************************************************************************************************/ void Register::sync() { - auto value = _device->device.readWord(_bar, _offset); - for(auto i = 0; i < _fields.length(); i++) - { - _fields[i]->updateValue(value); - } + auto value = _device->device.readWord(_bar, _offset); + for(auto i = 0; i < _fields.length(); i++) + { + _fields[i]->updateValue(value); + } } - +/*************************************************************************************************/ void Register::syncArray() { - for(quint32 i = 0; i < _arrayLength; i++) - { - auto value = _device->device.readWord(_bar, _offset + i*4); - for(auto i = 0; i < _fields.length(); i++) - { - _fields[i]->updateValue(value); - } - - receiveData(); - } - -} - -QVector Register::qntzr(QVector &data, quint32 sign, quint32 wordlength, quint32 fractionalLength, float maxLevel, bool integerOutput, bool useRound, bool twosCmpl) -{ + for(quint32 i = 0; i < _arrayLength; i++) + { + auto value = _device->device.readWord(_bar, _offset + i * 4); + for(auto i = 0; i < _fields.length(); i++) + { + _fields[i]->updateValue(value); + } + receiveData(); + } } - - - -//QVector Register::qntzr(QVector &data, -// quint32 sign, -// quint32 wordLength, -// quint32 fractionalLength, -// float maxLevel, -// bool integerOutput, -// bool useRound, -// bool twosCmpl) -//{ -// auto fullScale = -// powf(2.0f, wordLength - fractionalLength - sign) - 1 + -// (powf(2.0f, fractionalLength) - 1) / -// powf(2.0f, fractionalLength); -// if(maxLevel > 0) -// { -// if(fractionalLength > 0) -// { -// for(auto i = 0; i < data.length(); i++) -// { -// data[i] /= maxLevel; -// } -// } -// else -// { -// fullScale = maxLevel; -// } -// } - -// for(auto i = 0; i < data.length(); i++) -// { -// if(data[i] > fullScale) -// { -// data[i] = fullScale; -// } - -// if(data[i] < -fullScale) -// { -// data[i] = -fullScale; -// } -// } - -// QVector output; -// if(integerOutput) -// { -// for(auto i = 0; i < data.length(); i++) -// { -// qint32 out; -// if(useRound) -// { -// out = -// static_cast(roundf(data[i] / fullScale * -// (powf(2.0f, wordLength - sign) - 1))); -// } -// else -// { -// out = -// static_cast(floorf(data[i] / fullScale * -// (powf(2.0f, wordLength - sign) - 1))); -// } -// if(out < 0) -// { -// out += powf(2.0f, wordLength); -// } - -// output.push_back(out); -// } -// } -// else -// { -// for(auto i = 0; i < data.length(); i++) -// { -// qint32 out; -// if(useRound) -// { -// out = -// static_cast(roundf(data[i] / fullScale * -// (powf(2.0f, wordLength - sign) - 1)) / -// (fullScale * (powf(2.0f, wordLength - sign) - 1))); -// } -// else -// { -// out = -// static_cast(floorf(data[i] / fullScale * -// (powf(2.0f, wordLength - sign) - 1)) / -// (fullScale * (powf(2.0f, wordLength - sign) - 1))); -// } - -// output.push_back(out); -// } -// } - -// return output; -//} diff --git a/src/model/hardware/core/register/afe/Afe.cpp b/src/model/hardware/core/register/afe/Afe.cpp new file mode 100644 index 0000000..6397461 --- /dev/null +++ b/src/model/hardware/core/register/afe/Afe.cpp @@ -0,0 +1,102 @@ +#include "model/hardware/core/register/afe/Afe.h" + +void Afe::setActTerm(const AfeConfig afe) const +{ + quint32 value(0); + + value = (afe.actTermEn) ? 1 : 0; + this->_actTerm->actTermEn->setValue(value); + + value = (afe.lnaHpfDis) ? 1 : 0; + this->_actTerm->lnaHpfDis->setValue(value); + + this->_actTerm->lnaGainGbl->setValue(afe.lnaGainGbl); + + this->_actTerm->gblActiveTerm->setValue(afe.gblActiveTerm); + + this->_actTerm->activeTermIndRes->setValue(afe.activeTermIndRes); + + this->_actTerm->lnaInputClampLvl->setValue(afe.inputClampLvl); + + value = (afe.activeTermIndResEn) ? 1 : 0; + this->_actTerm->activeTermIndResEn->setValue(value); + + this->_actTerm->update(); +} + +void Afe::setLnaHpf(const AfeConfig afe) const +{ + this->_lnaHpf->lnaHpfProg->setValue(afe.lnaHpfProg); + this->_lnaHpf->update(); +} + +void Afe::setLowNf(const AfeConfig afe) const +{ + quint32 value = (afe.lowNf) ? 1 : 0; + this->_lowNf->lowNf->setValue(value); + + this->_lowNf->powModes->setValue(afe.powModes); + + this->_lowNf->update(); +} + +void Afe::setPga(const AfeConfig afe) const +{ + quint32 value(0); + + this->_pga->lpfProg->setValue(afe.lpfProg); + + value = (afe.pgaGain) ? 1 : 0; + this->_pga->pgaGain->setValue(value); + + value = (afe.pgaHpfDis) ? 1 : 0; + this->_pga->pgaHpfDis->setValue(value); + + value = (afe.pgaClampDis) ? 1 : 0; + this->_pga->pgaClampDis->setValue(value); + + value = (afe.pgaClampLvl) ? 1 : 0; + this->_pga->pgaClampLvl->setValue(value); + + this->_pga->update(); +} + +Afe::Afe(SonoDevice *device, quint32 offset) +{ + _actTerm = new ActiveTerm(device, offset); + _lnaHpf = new LnaHpf (device, offset); + _global = new Global (device, offset); + _lowNf = new LowNf (device, offset); + _pga = new Pga (device, offset); +} + +Afe::~Afe() +{ + delete _actTerm; + delete _lnaHpf; + delete _global; + delete _lowNf; + delete _pga; +} + +void Afe::setAfeParams(const AfeConfig afe) const +{ + this->setPga(afe); + this->setLowNf(afe); + this->setLnaHpf(afe); + this->setActTerm(afe); +} + +void Afe::setAfeGblPwr(const bool pwrdn) const +{ + quint32 value = pwrdn ? 1 : 0; + this->_lowNf->gblPdwn->setValue(value); + this->_lowNf->update(); +} + +void Afe::setReadRegEnable(const bool rdEn) const +{ + quint32 value = rdEn ? 1 : 0; + this->_global->regReadEn->setValue(value); + this->_global->update(); +} diff --git a/src/model/hardware/core/register/bpiFlash/BpiFlash.cpp b/src/model/hardware/core/register/bpiFlash/BpiFlash.cpp index 323f9b7..2f5ba6d 100644 --- a/src/model/hardware/core/register/bpiFlash/BpiFlash.cpp +++ b/src/model/hardware/core/register/bpiFlash/BpiFlash.cpp @@ -1,5 +1,14 @@ #include "model/hardware/core/register/bpiFlash/BpiFlash.h" -#include "model/hardware/core/register/fpgaProgram/FpgaProgram.h" + +template +T byteArray2UintBigEndian(QByteArray &byte) +{ + T data; + QDataStream in(byte); + in.setByteOrder(QDataStream::BigEndian); + in >> data; + return data; +} BpiFlash::BpiFlash(SonoDevice *device) { @@ -26,7 +35,7 @@ void BpiFlash::writeMcs(QByteArray &mcs) const for (quint8 i(0); i (mcsArray); mcsList.append(progData); mcsArray.clear(); diff --git a/src/model/hardware/core/register/fpgaProgram/FpgaProgram.cpp b/src/model/hardware/core/register/fpgaProgram/FpgaProgram.cpp index 099ef7f..53340d2 100644 --- a/src/model/hardware/core/register/fpgaProgram/FpgaProgram.cpp +++ b/src/model/hardware/core/register/fpgaProgram/FpgaProgram.cpp @@ -1,8 +1,9 @@ #include "model/hardware/core/register/fpgaProgram/FpgaProgram.h" -quint32 byteArray2Uint32BigEndian(QByteArray& byte) +template +T byteArray2UintBigEndian(QByteArray &byte) { - quint32 data; + T data; QDataStream in(byte); in.setByteOrder(QDataStream::BigEndian); in >> data; @@ -53,7 +54,7 @@ void FpgaProgram::program(QByteArray& bitFileData, quint8 number) //temp.append(bitFileData.at(i+progByte)); assert size temp.append(bitFileData[i+progByte]); - progData = byteArray2Uint32BigEndian(temp); + progData = byteArray2UintBigEndian (temp); _progData->slaveConfigData->setValue(progData); _progData->update(); @@ -177,5 +178,3 @@ bool FpgaProgram::ProgramStatus::getFpgaS2InitB() const // fpgaDoneStatus&=FPGA_S2_DONE; // return (fpgaDoneStatus!=0); //} - - diff --git a/src/model/hardware/core/register/sram/Sram.cpp b/src/model/hardware/core/register/sram/Sram.cpp index 91a7573..bd8eb0b 100644 --- a/src/model/hardware/core/register/sram/Sram.cpp +++ b/src/model/hardware/core/register/sram/Sram.cpp @@ -2,13 +2,14 @@ Sram::Sram(SonoDevice *device) { - _index = new Index (device); - _tx = new TxParams (device); - _txFocus = new TxParamsFocus (device); - _rx = new RxParams (device); - _rxDegree = new RxParamsDegree(device); - _rxPos = new RxParamsPos (device); - _rxDelay = new RxParamsDelay (device); + _index = new Index (device); + _tx = new TxParams (device); + _txFocus = new TxParamsFocus (device); + _rx = new RxParams (device); + _rxDegree = new RxParamsDegree (device); + _rxPos = new RxParamsPos (device); + _rxDelay = new RxParamsDelay (device); + _metaData = new SoftwareMetaData (device); } Sram::~Sram() @@ -20,6 +21,7 @@ Sram::~Sram() delete _rxDegree; delete _rxPos; delete _rxDelay; + delete _metaData; } void Sram::setSramIndex(quint32 &totalTxShotNumber, SramIndex *index) const @@ -69,4 +71,18 @@ void Sram::setSramRx(QVector &rxBeamFormerNumber, quint32 &focusTypeNumb this->_rxDelay->changeOffset(rxDelayBaseOffset ); // return to base offset address } +void Sram::setSramMetaData(QList &metaData) const +{ + this->_metaData->setSoftwareMetaData(metaData); + this->_metaData->updateArrayLong(META_DATA_INTERVAL, META_DATA_LENGTH); + + quint32 metaDataBaseOffset = this->_metaData->getCurrentOffset(); + + this->_metaData->changeOffset(META_DATA_OFFSET+metaDataBaseOffset); + + this->_metaData->updateArrayLong(META_DATA_INTERVAL, META_DATA_LENGTH); + + this->_metaData->changeOffset(metaDataBaseOffset); // return to base offset address +} + diff --git a/src/model/hardware/device/SonoDevice.cpp b/src/model/hardware/device/SonoDevice.cpp index 31c72fc..5a5b4fc 100644 --- a/src/model/hardware/device/SonoDevice.cpp +++ b/src/model/hardware/device/SonoDevice.cpp @@ -9,65 +9,48 @@ SonoDevice::SonoDevice() SonoDevice::~SonoDevice() { - for(auto i = 0; i < SW_BUFFER_NUM; i++) - { - delete[] _buffers[i]; - } + for(auto i = 0; i < SW_BUFFER_NUM; i++) + { + delete[] _buffers[i]; + } } void SonoDevice::init() { - device.init(); + device.init(); - for(auto i = 0; i < SW_BUFFER_NUM; i++) + for(auto i = 0; i < SW_BUFFER_NUM; i++) { - _buffers[i] = new char[BUFFER_SIZE]; + _buffers[i] = new char[BUFFER_SIZE]; memset(_buffers[i], 0, BUFFER_SIZE); } } void SonoDevice::startDma() { - device.writeWord(0, 0x8,1); + device.writeWord(0, 0x8, 1); } void SonoDevice::stopDma() { - device.writeWord(0, 0x8,0); + device.writeWord(0, 0x8, 0); } int SonoDevice::getCounter() { - auto temp = device.readWord(BAR, COUNTER_REG); + auto temp = device.readWord(BAR_BRAM, COUNTER_REG); return temp & COUNTER_MASK; } void SonoDevice::copy(int srcIndex, int dstIndex) { - auto src = device.getBufferPtr(srcIndex); - auto dst = _buffers[dstIndex]; - memcpy(dst, src, BUFFER_SIZE); + auto src = device.getBufferPtr(srcIndex); + auto dst = _buffers[dstIndex]; + memcpy(dst, src, BUFFER_SIZE); } -//void SonoDevice::show(int i) -//{ -// auto tmp = _buffers[i]; -// for(auto j = 0; j < 80; j += 8) -// { - -// quint32 res = 0; -// quint32 res2 = 0; -// res = tmp[j] | (tmp[j + 1] << 8) | (tmp[j + 2] << 16) | (tmp[j + 3] << 24); -// res2 = (tmp[j + 4] << 32) | (tmp[j + 5] << 40) | (tmp[j + 6] << 48) | (tmp[j + 7] << 56); -// qDebug() << QString("%1 %2").arg(QString::number(res2, -// 10).rightJustified( -// 6, -// '0')).arg(QString::number(res, 10)); -// } -//} - const char* SonoDevice::getBufferPtr(int index) { - return _buffers[index]; + return _buffers[index]; } diff --git a/src/model/hardware/service/BHardwarePacket.cpp b/src/model/hardware/service/BHardwarePacket.cpp new file mode 100644 index 0000000..a55c762 --- /dev/null +++ b/src/model/hardware/service/BHardwarePacket.cpp @@ -0,0 +1,61 @@ +#include "model/hardware/service/BHardwarePacket.h" + +#include "model/ultrasoundModule/metadata/BMetadata.h" +#include "model/ultrasoundModule/metadata/HardwareMetadata.h" +#include "model/ultrasoundModule/metadata/UsMetadataBag.h" + +BHardwarePacket::BHardwarePacket() +{ + _totalBLineNumber = 0; + _index = 0; +} + +void BHardwarePacket::decode(QByteArray buffer) +{ + HardwarePacket::decode(buffer); + + auto bLineNumber = Extract16BitValue(buffer, B_LINE_NO_INDEX); + _totalBLineNumber += bLineNumber; + _bPointNumber = Extract16BitValue(buffer, B_POINT_NO_INDEX); + + auto bLineByteCount = _bPointNumber * 4; + + for(auto i = 0; i < bLineNumber; i++) + { + for(auto j = 0; j < bLineByteCount; j++) + { + _data.push_back(buffer[PAYLOAD_INDEX + i * bLineByteCount + j]); + _index++; + } + } +} + +UsPacket BHardwarePacket::getUsPacket(int fps) +{ + BMetadata metadata; + metadata.width = _bPointNumber; + metadata.height = _totalBLineNumber; + metadata.frameCounter = frameCounter; + QVariant var; + var.setValue(metadata); + + UsMetadataBag bag; + bag.appendMetadata(var); + + UsData data; + data.setData(_data); + data.setMetadataBag(bag); + + bag.clear(); + HardwareMetadata hardwareMetadata; + hardwareMetadata.dataType = static_cast(type); + hardwareMetadata.fps = fps; + var.setValue(hardwareMetadata); + bag.appendMetadata(var); + + UsPacket packet; + packet.setBData(data); + packet.setMetadataBag(bag); + + return packet; +} diff --git a/src/model/hardware/service/HardwarePacket.cpp b/src/model/hardware/service/HardwarePacket.cpp new file mode 100644 index 0000000..cb076d5 --- /dev/null +++ b/src/model/hardware/service/HardwarePacket.cpp @@ -0,0 +1,21 @@ +#include "model/hardware/service/HardwarePacket.h" + +HardwarePacket::HardwarePacket() +{ +} + +void HardwarePacket::decode(QByteArray buffer) +{ + batch = Extract16BitValue(buffer, BATCH_INDEX); + subBatch = static_cast(buffer[SUB_BATCH_INDEX]); + type = static_cast(buffer[TYPE_INDEX]); + frameCounter = static_cast(buffer[FRAME_COUNTER_INDEX]); +} + +quint16 HardwarePacket::Extract16BitValue(QByteArray buffer, int index) +{ + auto temp = buffer[index] & 0xFF; + temp |= (((buffer[index + 1] & 0xFF) << 8) & 0xFF00); + + return static_cast(temp); +} diff --git a/src/model/hardware/service/HardwarePacketEngine.cpp b/src/model/hardware/service/HardwarePacketEngine.cpp new file mode 100644 index 0000000..3da55c6 --- /dev/null +++ b/src/model/hardware/service/HardwarePacketEngine.cpp @@ -0,0 +1,57 @@ +#include "model/hardware/service/HardwarePacketEngine.h" + +#include "model/hardware/service/BHardwarePacket.h" + +#include + +HardwarePacketEngine::HardwarePacketEngine() +{ + _lastBatch = -1; + _hardwarePacket = Q_NULLPTR; +} + +void HardwarePacketEngine::newData(QByteArray buffer, bool flush) +{ + auto batch = static_cast(buffer[BATCH_INDEX] | (buffer[BATCH_INDEX + 1] << 8)); + auto type = buffer[TYPE_INDEX]; + + if(batch == _lastBatch) + { + _hardwarePacket->decode(buffer); + } + else + { + auto time = _elapsedTimer.elapsed(); + qDebug() << time << " " << batch; + if(_hardwarePacket != Q_NULLPTR) + { + auto packet = _hardwarePacket->getUsPacket(1000 / time); + emit newPacketReady(packet); + + delete _hardwarePacket; + _hardwarePacket = Q_NULLPTR; + } + + _elapsedTimer.start(); + switch(type) + { + case 0: + _hardwarePacket = new BHardwarePacket(); + break; + } + + _hardwarePacket->decode(buffer); + if(flush) + { + auto packet = _hardwarePacket->getUsPacket(60000 / time); + emit newPacketReady(packet); + + delete _hardwarePacket; + _hardwarePacket = Q_NULLPTR; + } + else + { + _lastBatch = batch; + } + } +} diff --git a/src/model/scenarioGenerator/ScenarioGenerator.cpp b/src/model/scenarioGenerator/ScenarioGenerator.cpp new file mode 100644 index 0000000..d544b6c --- /dev/null +++ b/src/model/scenarioGenerator/ScenarioGenerator.cpp @@ -0,0 +1,443 @@ +#include "model/scenarioGenerator/ScenarioGenerator.h" + +#include "model/backendImageProcessor/Bip.h" +#include "viewModel/MainViewModel.h" +#include "model/scenarioGenerator/utils/Macros.h" +#include "model/databaseManager/DatabaseManager.h" +#include "model/databaseManager/dto/ProbeProperties/DbmProbeProperties.h" +#include "model/databaseManager/dto/Hardware/DbmApodizationLut.h" +#include "model/databaseManager/dto/Hardware/DbmLpf.h" +#include "model/databaseManager/dto/Hardware/DbmLineFilter.h" + +#include "model/bipTester/BipTester.h" + +SINGLETON_DEF(ScenarioGenerator) + +/*************************************************************************************************/ +/** + * @brief Ctor + */ +/*************************************************************************************************/ +ScenarioGenerator::ScenarioGenerator() : UsModule(this) +{ +} + +/*************************************************************************************************/ +/** + * @brief Dtor + */ +/*************************************************************************************************/ +ScenarioGenerator::~ScenarioGenerator() +{ +} + +/*************************************************************************************************/ +/** + * @brief ScenarioGenerator::getSystemParameters + * @return + */ +/*************************************************************************************************/ +ScenGenSystemParameters_t ScenarioGenerator::getSystemParameters() +{ + auto res = requestDataFromDatabase(EDatabaseRequest::getSysParameters, {}); + auto data = translateDatabaseData(res.getValueList()); + + return ScenGenSystemParameters_t(data); +} + +/*************************************************************************************************/ +/** + * @brief ScenarioGenerator::getApodization + */ +/*************************************************************************************************/ +void ScenarioGenerator::getApodization(ScenGenDatabase_t& database) +{ + auto res = requestDataFromDatabase(EDatabaseRequest::getApodizationLut, {}); + auto data = translateDatabaseData(res.getValueList()); + + database.apodization1 = QVector::fromList(data.case1); + database.apodization2 = QVector::fromList(data.case2); + database.apodization3 = QVector::fromList(data.case3); + database.apodization4 = QVector::fromList(data.case4); +} + +/*************************************************************************************************/ +/** + * @brief ScenarioGenerator::getLpf + */ +/*************************************************************************************************/ +void ScenarioGenerator::getLpf(ScenGenDatabase_t& database) +{ + auto res = requestDataFromDatabase(EDatabaseRequest::getLpf, {}); + auto data = translateDatabaseData(res.getValueList()); + + database.lpf.clear(); + for(auto i = 0; i < data.lpf.length(); i++) + { + database.lpf.append(static_cast(data.lpf[i])); + } +} + +/*************************************************************************************************/ +/** + * @brief ScenarioGenerator::getLineFilter + */ +/*************************************************************************************************/ +void ScenarioGenerator::getLineFilter(ScenGenDatabase_t& database) +{ + auto res = requestDataFromDatabase(EDatabaseRequest::getLineFilter, {}); + auto data = translateDatabaseData(res.getValueList()); + + database.lineFilterLut.clear(); + for(auto i = 0; i < data.lineFilterData.length(); i++) + { + QList temp; + for(auto j = 0; j < data.lineFilterData[i].length(); j++) + { + temp.push_back(static_cast(data.lineFilterData[i][j])); + } + database.lineFilterLut.append(temp); + } +} + +/*************************************************************************************************/ +/** + * @brief ScenarioGenerator::getScenGenDatabase + */ +/*************************************************************************************************/ +ScenGenDatabase_t ScenarioGenerator::getScenGenDatabase() +{ + ScenGenDatabase_t database; + + getApodization(database); + getLpf(database); + getLineFilter(database); + + return database; +} + +/*************************************************************************************************/ +/** + * @brief ScenarioGenerator::requestDataFromDatabase + * @param request + * @param args + * @return + */ +/*************************************************************************************************/ +CommandResult ScenarioGenerator::requestDataFromDatabase(EDatabaseRequest::eDatabaseRequest request, + const QList args) +{ + auto arg = QList{ request }; + arg.append(args); + + return sendSyncCommand(ECommandType::getData, DB_MAN_NAME, arg); +} + +/*************************************************************************************************/ +/** + * @brief Hook is the first hook to be called after the object has been created and moved to + * its own thread + * @details The purpose of this hook is mainly to instantiate internal children so that they are + * spawned in the target thread + * @return nething + */ +/*************************************************************************************************/ +void ScenarioGenerator::afterThreadStart() +{ +} + +/*************************************************************************************************/ +/** + * @brief Hook is the second hook to be called after the object has been created and moved to + * its own thread + * @details The purpose of this hook is mainly to connect command and data path of the module to + * desired destinations, connection to core signals if necesserly goes here too + * @note This is prohibited to send commands in this hook, though the command itself shall receive + * its destination and be executed, but considering the fact that not all modules have their init + * called, the command chain is not necesserly complete and overall outcome may not be desired + */ +/*************************************************************************************************/ +void ScenarioGenerator::init() +{ + _core = new ScenGenCore(); + _computationalCore = new ComputationalCore(); + + connectCommandPath(); + connectCommandPath(); + connectCommandPath(); + + connect(_core, + &ScenGenCore::softwareScenarioReady, + this, + &ScenarioGenerator::newSoftwareScenario); + + connect(_core, + &ScenGenCore::hardwareScenarioReady, + this, + &ScenarioGenerator::newHardwareScenario); + + connect(_core, + &ScenGenCore::aoReady, + this, + &ScenarioGenerator::newAo); + + connect(_core, + &ScenGenCore::dtgcReady, + this, + &ScenarioGenerator::newDtgc); + + connect(_core, + &ScenGenCore::lineFilterReady, + this, + &ScenarioGenerator::newLineFilter); +} + +/*************************************************************************************************/ +/** + * @brief Hook is called after inits of all \sa UsModule s has been called + * @details The purpose of this hook is mainly to start any internal + * thread and functionality if any exist, requests can work here + * @note after this hook normal life cycle begins + */ +/*************************************************************************************************/ +void ScenarioGenerator::start() +{ + auto sysParam = getSystemParameters(); + _core->setSystemParameters(sysParam); + + auto database = getScenGenDatabase(); + _core->updateDatabase(database); +} + +/*************************************************************************************************/ +/** + * @brief ScenarioGenerator::packetHandler + * @param packet + */ +/*************************************************************************************************/ +void ScenarioGenerator::packetHandler(const UsPacket& packet) +{ +} + +/*************************************************************************************************/ +/** + * @brief Method to process incoming requests + * @details It is called from base class when ever a valid request is destined + * for our object + * @return nothing + */ +/*************************************************************************************************/ +void ScenarioGenerator::commandHandler(const CommandRequest& request) +{ + switch(request.getCommandType()) + { + case ECommandType::bModeSettingChanged: + { + auto setting = GET_VALUE(request, 0, DataBModeSetting_t); + _core->updateModeBSettingParams(setting); + DataImage_t t; + t.sonoBImageH = 600; + t.sonoBImageW = 600; + _core->updateImageParams(t); + _core->process(); + if(setting.hdZoom) + { + ScenGenSoftwareOutput_t senGenSoftwarOutput = _core->getSoftwareValues(); + _computationalCore->setSoftwareParams(senGenSoftwarOutput); + auto zoomGate = _computationalCore->getZoomGate(); + qDebug() << "height: " << zoomGate.endAxial - zoomGate.startAxial << + "|__| width: " << zoomGate.endAzimuth - zoomGate.startAzimuth; + _core->updateHDZoomGate(zoomGate); + } + else + { + _computationalCore->zoomOff(); + } + } + break; + + case ECommandType::zoomGateSizeChanged: + { + if(_computationalCore->getZoomEnable()) + { + auto stepCount = GET_VALUE(request, 0, qint16); + + _computationalCore->changeSize(stepCount); + auto zoomGate = _computationalCore->getZoomGate(); + qDebug() << "step Count: " << stepCount << "|__| height: " << + zoomGate.endAxial - zoomGate.startAxial << " | width: " << + zoomGate.endAzimuth - zoomGate.startAzimuth; + _core->updateHDZoomGate(zoomGate); + } + } + break; + + case ECommandType::zoomGateLocationChanged: + { + auto x = GET_VALUE(request, 0, int); + auto z = GET_VALUE(request, 1, int); + _computationalCore->changeLocation(x, z); + auto zoomGate = _computationalCore->getZoomGate(); + qDebug() << " |__| StartZ: " << zoomGate.startAxial << " |__| EndZ: " << + zoomGate.endAxial << " |__| StartX: " << zoomGate.startAzimuth / 3.14F * 180 << + " |__| EndX: " << + zoomGate.endAzimuth / 3.14F * 180.0F; + + _core->updateHDZoomGate(zoomGate); + } + break; + + case ECommandType::bModeDisplayChanged: + { + auto setting = GET_VALUE(request, 0, DataBModeDisplay_t); + _core->updateModeBDisplayParams(setting); + _core->process(); + } + break; + + case ECommandType::tgcChanged: + { + auto setting = GET_VALUE(request, 0, DataTgc_t); + _core->updateTgcParams(setting); + + DataImage_t t; + t.sonoBImageH = 1000; + t.sonoBImageW = 1000; + _core->updateImageParams(t); + + _core->process(); + } + break; + + case ECommandType::changeMode: + { + auto newMode = GET_VALUE(request, 0, EImageMode::eImageMode); + _core->changeMode(newMode); + } + break; + + case ECommandType::probeChanged: + { + auto temp = GET_VALUE(request, 0, SsmProbeProperties_t); + ScenGenProbeProperties_t probeProps(temp); + _core->setProbeParameters(probeProps); + _core->process(); + break; + } + + case ECommandType::resendParam: + { + _core->process(); + } + break; + + case ECommandType::resume: + { + _core->start(); + _core->process(); + } + break; + + case ECommandType::pause: + { + _core->stop(); + } + break; + } + _eventReceiver->sendResponse(request, ECommandResult::Success); +} + +/*************************************************************************************************/ +/** + * @brief Method to process incoming requests + * @details It is called from base class when ever a valid request is destined + * for our object + * @return nothing + */ +/*************************************************************************************************/ +void ScenarioGenerator::processScenGenCommand(bool result, const CommandRequest& request) +{ + if(!result) + { + fail(request); + } + else + { + pass(request); + } +} + +/*************************************************************************************************/ +/** + * @brief ScenarioGenerator::newHardwareScenario + */ +/*************************************************************************************************/ +void ScenarioGenerator::newHardwareScenario() +{ +} + +/*************************************************************************************************/ +/** + * @brief ScenarioGenerator::newSoftwareScenario + */ +/*************************************************************************************************/ +void ScenarioGenerator::newSoftwareScenario() +{ + sendScenGenSoftwareUpdateCommand(); +} + +/*************************************************************************************************/ +/** + * @brief Method to process incoming requests + * @details It is called from base class when ever a valid request is destined + * for our object + * @return nothing + */ +/*************************************************************************************************/ +void ScenarioGenerator::sendScenGenSoftwareUpdateCommand() +{ + QVariant var; + var.setValue(_core->getSoftwareValues()); + sendAsyncCommand(ECommandType::changeScenParam, BIP_NAME, {var}); +} + +/*************************************************************************************************/ +/** + * @brief ScenarioGenerator::newAo + * @param ao + */ +/*************************************************************************************************/ +void ScenarioGenerator::newAo(quint32 ao) +{ +} + +/*************************************************************************************************/ +/** + * @brief ScenarioGenerator::newDtgc + * @param dtgc + */ +/*************************************************************************************************/ +void ScenarioGenerator::newDtgc(QVector dtgc) +{ +} + +/*************************************************************************************************/ +/** + * @brief ScenarioGenerator::newLineFilter + * @param lineFilter + */ +/*************************************************************************************************/ +void ScenarioGenerator::newLineFilter(QVector lineFilter) +{ +} + +/*************************************************************************************************/ +/** + * + */ +/*************************************************************************************************/ +template +T ScenarioGenerator::translateDatabaseData(const QList result) +{ + return result[0].value(); +} diff --git a/src/model/scenarioGenerator/core/ComputationalCore.cpp b/src/model/scenarioGenerator/core/ComputationalCore.cpp new file mode 100644 index 0000000..f6379b8 --- /dev/null +++ b/src/model/scenarioGenerator/core/ComputationalCore.cpp @@ -0,0 +1,328 @@ +#include "../../../../include/model/scenarioGenerator/core/ComputationalCore.h" + +/*************************************************************************************************/ +ComputationalCore::ComputationalCore() +{ +} + +/*************************************************************************************************/ +void ComputationalCore::calculateFrameSize() +{ + _frameWidth = _bScanConversion.bMaxScanAz - _bScanConversion.bMinScanAz; + _frameDepth = _bScanConversion.bMaxScanAx - _bScanConversion.bMinScanAx; + _frameMinDepth = _bScanConversion.bMinScanAx; + _frameMaxDepth = _bScanConversion.bMaxScanAx; +} + +/*************************************************************************************************/ +void ComputationalCore::setInitialSize() +{ + if(scanIsLinear(_bScanConversion)) + { + _initAzimuthSize = LINEAR_INIT_WIDTH; + _initAxialSize = LINEAR_INIT_DEPTH; + _azimuthStep = LINEAR_STEP; + _axialStep = LINEAR_STEP; + } + else + { + if(_frameWidth > CONVEX_INIT_ANGLE) + { + _initAzimuthSize = CONVEX_INIT_ANGLE; + } + else + { + _initAzimuthSize = _frameWidth; + } + if(_frameDepth > CONVEX_INIT_DEPTH) + { + _initAxialSize = CONVEX_INIT_DEPTH; + } + else + { + _initAxialSize = _frameDepth; + } + _azimuthStep = CONVEX_ANGLE_STEP; + _axialStep = CONVEX_LENGTH_STEP; + } +} + +/*************************************************************************************************/ +void ComputationalCore::setSoftwareParams(ScenGenSoftwareOutput_t& softwareParams) +{ + _softwareParams = softwareParams; + _bScanConversion = _softwareParams.scanConversionProps.at(0); + calculateFrameSize(); + setInitialSize(); + init(); +} + +/*************************************************************************************************/ +void ComputationalCore::changeSize(int stepCount) +{ + int unit = abs(stepCount) / stepCount; + for(int i = 0; i < abs(stepCount); ++i) + { + if(canChangeAxialSize(unit)) + { + applyAxialSizeChange(unit); + } + if(canChangeAzimuthSize(unit)) + { + applyAzimuthSizeChange(unit); + } + } +} + +/*************************************************************************************************/ +void ComputationalCore::applyAxialSizeChange(int unit) +{ + float upSideChange = (static_cast(unit) / 2.0F) * _axialStep; + float downSideChange = (static_cast(unit) / 2.0F) * _axialStep; + + _zoomGate.startAxial -= upSideChange; + _zoomGate.endAxial += downSideChange; +} + +/*************************************************************************************************/ +void ComputationalCore::applyAzimuthSizeChange(int unit) +{ + float leftChange = (static_cast(unit) / 2.0F) * _azimuthStep; + float rightChange = (static_cast(unit) / 2.0F) * _azimuthStep; + if(_zoomGate.startAzimuth - leftChange > -(_frameWidth / 2)) + { + _zoomGate.startAzimuth -= leftChange; + } + else + { + _zoomGate.startAzimuth = -(_frameWidth / 2); + } + if(_zoomGate.endAzimuth + rightChange < (_frameWidth / 2)) + { + _zoomGate.endAzimuth += rightChange; + } + else + { + _zoomGate.endAzimuth = (_frameWidth / 2); + } +} + +/*************************************************************************************************/ +bool ComputationalCore::canChangeAxialSize(int unit) +{ + return isZoomGateAxialSurroundedInImage(unit); +} + +/*************************************************************************************************/ +bool ComputationalCore::canChangeAzimuthSize(int unit) +{ + return isZoomGateAzimuthSurroundedInImage(unit); +} + +/*************************************************************************************************/ +bool ComputationalCore::isZoomGateAxialSurroundedInImage(int unit) +{ + auto currentDepth = _zoomGate.endAxial - _zoomGate.startAxial; + auto newDepth = currentDepth + unit * _axialStep; + auto smalerThanImageAxial = newDepth <= _frameDepth; + auto biggerThanInitAxial = newDepth >= _initAxialSize; + + return smalerThanImageAxial && biggerThanInitAxial; +} + +/*************************************************************************************************/ +bool ComputationalCore::isZoomGateAzimuthSurroundedInImage(int unit) +{ + auto currentWidth = _zoomGate.endAzimuth - _zoomGate.startAzimuth; + auto newWidth = currentWidth + unit * _azimuthStep; + auto smalerThanImageAzimuth = newWidth <= _frameWidth; + auto biggerThanInitAzimuth = newWidth >= _initAzimuthSize; + + return smalerThanImageAzimuth && biggerThanInitAzimuth; +} + +/*************************************************************************************************/ +ScenGenZoomGate_t ComputationalCore::getZoomGate() +{ + return _zoomGate; +} + +/*************************************************************************************************/ +bool ComputationalCore::getZoomEnable() +{ + return _zoomON; +} + +/*************************************************************************************************/ +void ComputationalCore::zoomOff() +{ + _zoomON = false; +} + +/*************************************************************************************************/ +void ComputationalCore::init() +{ + initZoomGate(); +} + +/*************************************************************************************************/ +bool ComputationalCore::scanIsLinear(ScenGenScanConversionConfig_t& bScnConversion) +{ + return bScnConversion.linear && !bScnConversion.virtualConvex; +} + +/*************************************************************************************************/ +bool ComputationalCore::scanIsConvex(ScenGenScanConversionConfig_t& bScnConversion) +{ + return !bScnConversion.linear; +} + +/*************************************************************************************************/ +bool ComputationalCore::scanIsVirtualConvex(ScenGenScanConversionConfig_t& bScnConversion) +{ + return bScnConversion.linear && bScnConversion.virtualConvex; +} + +/*************************************************************************************************/ +void ComputationalCore::calculateGateDepth(float gateDepth) +{ + auto halfDepth = _frameDepth / 2.0F; + _zoomGate.startAxial = halfDepth - (gateDepth / 2.0F); + _zoomGate.endAxial = _zoomGate.startAxial + gateDepth; +} + +/*************************************************************************************************/ +void ComputationalCore::calculateMinMaxAzimuth(float gateWidth) +{ + _zoomGate.startAzimuth = -(gateWidth / 2.0F); + _zoomGate.endAzimuth = +(gateWidth / 2.0F); +} + +/*************************************************************************************************/ +void ComputationalCore::initZoomGate() +{ + _zoomON = true; + if(scanIsLinear(_bScanConversion)) + { + _zoomGate.linear = true; + _zoomGate.VirtualConvex = false; + } + else + if(scanIsVirtualConvex(_bScanConversion)) + { + _zoomGate.linear = true; + _zoomGate.VirtualConvex = true; + } + else + if(scanIsConvex(_bScanConversion)) + { + _zoomGate.linear = false; + _zoomGate.VirtualConvex = false; + } + + setZoomGateDefaults(); +} + +/*************************************************************************************************/ +void ComputationalCore::setZoomGateDefaults() +{ + calculateMinMaxAzimuth(_initAzimuthSize); + calculateGateDepth(_initAxialSize); +} + +/*************************************************************************************************/ +void ComputationalCore::changeLocation(int difX, int difZ) +{ + changeGateLocation(difX, difZ, _azimuthStep, _axialStep); +} + +/*************************************************************************************************/ +void ComputationalCore::changeAzimuthLocation(float azimuthStep, int xUnit) +{ + auto cahngeStartAzimuth = canMinAzimuthLocChange(_zoomGate.startAzimuth + xUnit * azimuthStep); + auto changeEndAzimuth = canMaxAzimuthLocChange(_zoomGate.endAzimuth + xUnit * azimuthStep); + if(cahngeStartAzimuth && changeEndAzimuth) + { + _zoomGate.startAzimuth = _zoomGate.startAzimuth + xUnit * azimuthStep; + _zoomGate.endAzimuth = _zoomGate.endAzimuth + xUnit * azimuthStep; + } +} + +/*************************************************************************************************/ +void ComputationalCore::changeAxialLocation(float axialStep, int zUnit) +{ + auto changeStartAxial = canMinAxialLocChange(_zoomGate.startAxial + zUnit * axialStep); + auto changeEndAxial = canMaxAxialLocChange(_zoomGate.endAxial + zUnit * axialStep); + if(changeStartAxial && changeEndAxial) + { + _zoomGate.startAxial = _zoomGate.startAxial + zUnit * axialStep; + _zoomGate.endAxial = _zoomGate.endAxial + zUnit * axialStep; + } +} + +/*************************************************************************************************/ +void ComputationalCore::changeGateLocation(int difX, int difZ, float azimuthStep, float axialStep) +{ + auto zUnit = abs(difZ) / difZ; + auto xUnit = abs(difX) / difX; + for(int i = 0; i < abs(difX); ++i) + { + changeAzimuthLocation(azimuthStep, xUnit); + } + for(int i = 0; i < abs(difZ); ++i) + { + changeAxialLocation(axialStep, zUnit); + } +} + +/*************************************************************************************************/ +bool ComputationalCore::canMinAzimuthLocChange(float location) +{ + auto zoomGateWidth = _zoomGate.endAzimuth - _zoomGate.startAzimuth; + auto minFovlimit = -(_frameWidth / 2.0F); + auto maxFovlimit = (_frameWidth / 2.0F); + if(location >= minFovlimit && location <= maxFovlimit - zoomGateWidth) + { + return true; + } + + return false; +} + +/*************************************************************************************************/ +bool ComputationalCore::canMaxAzimuthLocChange(float location) +{ + auto maxFovlimit = (_frameWidth / 2.0F); + auto minFovlimit = -(_frameWidth / 2.0F); + auto zoomGateWidth = _zoomGate.endAzimuth - _zoomGate.startAzimuth; + if(location <= maxFovlimit && location >= minFovlimit + zoomGateWidth) + { + return true; + } + + return false; +} + +/*************************************************************************************************/ +bool ComputationalCore::canMinAxialLocChange(float location) +{ + auto zoomGateHeight = _zoomGate.endAxial - _zoomGate.startAxial; + if(location >= _frameMinDepth && location <= _frameMaxDepth - zoomGateHeight) + { + return true; + } + + return false; +} + +/*************************************************************************************************/ +bool ComputationalCore::canMaxAxialLocChange(float location) +{ + auto zoomGateHeight = _zoomGate.endAxial - _zoomGate.startAxial; + if(location <= _frameMaxDepth && location >= _frameMinDepth + zoomGateHeight) + { + return true; + } + + return false; +} diff --git a/src/model/scenarioGenerator/core/ScenGenCore.cpp b/src/model/scenarioGenerator/core/ScenGenCore.cpp new file mode 100644 index 0000000..4a557aa --- /dev/null +++ b/src/model/scenarioGenerator/core/ScenGenCore.cpp @@ -0,0 +1,504 @@ +#include "model/scenarioGenerator/core/ScenGenCore.h" + +#include "model/scenarioGenerator/utils/Macros.h" +#include "model/scenarioGenerator/core/general/Calculation.h" +#include "model/scenarioGenerator/core/scenario/B/BModeScenario.h" +#include "model/scenarioGenerator/core/scenario/Bm/BmModeScenario.h" + +/*************************************************************************************************/ +/** + * @brief Ctor + */ +/*************************************************************************************************/ +ScenGenCore::ScenGenCore() +{ + _scenarioParamChanged = false; + _outputSizeParamChanged = false; + _isStarted = false; +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::process + */ +/*************************************************************************************************/ +void ScenGenCore::process() +{ + if(!_isStarted) + { + return; + } + + calculateScenarioIndependentSoftwareValues(); + + if(_scenarioParamChanged) + { + calculateScenarioDependentValues(); + +//for rx test maybe + updateRegs(); + emit hardwareScenarioReady(); + } + else + if(_outputSizeParamChanged) + { + calculateScanConvValues(); + } + + _scenarioParamChanged = false; + _outputSizeParamChanged = false; + + emit softwareScenarioReady(); +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::changeMode + * @param mode + */ +/*************************************************************************************************/ +void ScenGenCore::changeMode(EImageMode::eImageMode mode) +{ + _mode = mode; +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::start + */ +/*************************************************************************************************/ +void ScenGenCore::start() +{ + _isStarted = true; +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::stop + */ +/*************************************************************************************************/ +void ScenGenCore::stop() +{ + _isStarted = false; +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::updateModeBSettingParams + * @param setting + */ +/*************************************************************************************************/ +void ScenGenCore::updateModeBSettingParams(DataBModeSetting_t setting) +{ + _userParams.enhanceB = static_cast(setting.enhance); + _userParams.rejectB = static_cast(setting.reject); + _userParams.sri = static_cast(setting.sri); + _userParams.persist = static_cast(setting.persist); + _userParams.frameFilterMode = static_cast(setting.frameFilter); + + _userParams.dynamicContrastBSelector = static_cast(setting.dynamicContrast); + + _userParams.gainB = static_cast(setting.gainB); + + if(_userParams.cri != setting.cri) + { + _userParams.cri = static_cast(setting.cri); + _scenarioParamChanged = true; + } + + if(_userParams.oti != setting.oti) + { + _userParams.oti = static_cast(setting.oti); + _scenarioParamChanged = true; + } + + if(_userParams.focusFrequencyCompound != setting.ffc) + { + _userParams.focusFrequencyCompound = setting.ffc; + _scenarioParamChanged = true; + } + + if(_userParams.harmonicImaging != setting.hi) + { + _userParams.harmonicImaging = setting.hi; + _scenarioParamChanged = true; + } + + if(_userParams.pulseInversion != setting.pi) + { + _userParams.pulseInversion = setting.pi; + _scenarioParamChanged = true; + } + + if(_userParams.virtualConvex != setting.virtualConvex) + { + _userParams.virtualConvex = setting.virtualConvex; + _scenarioParamChanged = true; + } + + if(_userParams.angle != setting.angle) + { + _userParams.angle = static_cast(setting.angle); + _scenarioParamChanged = true; + } + + if(_userParams.frequency != setting.frequency) + { + _userParams.frequency = static_cast(setting.frequency); + _scenarioParamChanged = true; + } + + if(_userParams.lineDensity != setting.lineDensity) + { + _userParams.lineDensity = static_cast(setting.lineDensity); + _scenarioParamChanged = true; + } + + if(_userParams.criFilter != setting.criFilter) + { + _userParams.criFilter = static_cast(setting.criFilter); + _scenarioParamChanged = true; + } + + if(_userParams.lineFilter != setting.lineFilter) + { + _userParams.lineFilter = static_cast(setting.lineFilter); + calculateLineFilterValues(); + } + + if(_userParams.aoB != setting.ao) + { + _userParams.aoB = static_cast(setting.ao); + calculateAoValues(); + } + + if(_userParams.depth != setting.depth) + { + _userParams.depth = setting.depth; + _scenarioParamChanged = true; + } + + if(_userParams.focusNumber != setting.focusNumber) + { + _userParams.focusNumber = static_cast(setting.focusNumber); + _scenarioParamChanged = true; + } + + if(_userParams.focus != setting.focusPoints) + { + _userParams.focus = static_cast(setting.focusPoints); + _scenarioParamChanged = true; + } + + if(_userParams.hdZoom != setting.hdZoom) + { + _userParams.hdZoom = setting.hdZoom; + _scenarioParamChanged = true; + } +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::updateModeBDisplayParams + * @param setting + */ +/*************************************************************************************************/ +void ScenGenCore::updateModeBDisplayParams(DataBModeDisplay_t setting) +{ + _userParams.grayMapB.clear(); + _userParams.grayMapB.append(setting.graymap); + _userParams.tintMapBSelector = static_cast(setting.tintmap); +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::updateTgcParams + * @param setting + */ +/*************************************************************************************************/ +void ScenGenCore::updateTgcParams(DataTgc_t setting) +{ + _userParams.dtgc = setting.tgc; + calculateDtgcValues(); +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::updateImageParams + * @param setting + */ +/*************************************************************************************************/ +void ScenGenCore::updateImageParams(DataImage_t setting) +{ + _userParams.X = setting.sonoBImageW; + _userParams.Z = setting.sonoBImageH; + + _outputSizeParamChanged = true; +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::updateDatabase + * @param database + */ +/*************************************************************************************************/ +void ScenGenCore::updateDatabase(ScenGenDatabase_t database) +{ + _database = database; +} + +/*************************************************************************************************/ +/** + * @brief Set the value for probe properties and re-runs the scen dependent algorithm, + * @param value probe properties + * @return true + */ +/*************************************************************************************************/ +void ScenGenCore::setProbeParameters(ScenGenProbeProperties_t value) +{ + _probeParams.setProbeProps(value); + _database.atgcB = value.AtgcB.toVector(); + _database.atgcD = value.AtgcD.toVector(); + _database.atgcPw = value.AtgcPW.toVector(); + _database.atgcReserve.fromList(value.AtgcReserve); + _scenarioParamChanged = true; +} + +/*************************************************************************************************/ +/** + * @brief Set the value for system parameters + * @param value system parameters + * @return true + */ +/*************************************************************************************************/ +void ScenGenCore::setSystemParameters(ScenGenSystemParameters_t value) +{ + _systemParams = value; +} + +/*************************************************************************************************/ +/** + * @brief Return the latest software output calculated + * @return lastest software output + */ +/*************************************************************************************************/ +ScenGenSoftwareOutput_t ScenGenCore::getSoftwareValues() +{ + return _softwareOutput; +} + +/*************************************************************************************************/ +/** + * @brief Calculate the scenario dependent values + */ +/*************************************************************************************************/ +void ScenGenCore::calculateScenarioDependentValues() +{ + calcSecondaryProbeProps(); + + //update regs + + auto scenario = createScenario(); + + scenario->generate(); + + _softwareOutput.scanConversionProps = scenario->softwareOutput.scanConversionProps; + _softwareOutput.scenarioDependent = scenario->softwareOutput.scenarioDependent; + _softwareOutput.outputWidth = _userParams.X; + _softwareOutput.outputHeight = _userParams.Z; + + _hardwareOutput = scenario->hardwareOuput; + + delete scenario; +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::calculateScenarioIndependentSoftwareValues + */ +/*************************************************************************************************/ +void ScenGenCore::calculateScenarioIndependentSoftwareValues() +{ + _softwareOutput.enhanceB = _userParams.enhanceB; + _softwareOutput.rejectB = _userParams.rejectB; + _softwareOutput.sri = _userParams.sri; + _softwareOutput.persist = _userParams.persist; + _softwareOutput.frameFilterMode = _userParams.frameFilterMode; + _softwareOutput.dynamicContrastBSelector = _userParams.dynamicContrastBSelector; + _softwareOutput.tintMapBSelector = _userParams.tintMapBSelector; + _softwareOutput.grayMapB = _userParams.grayMapB; + _softwareOutput.cri = _userParams.cri; + _softwareOutput.criFilterMode = _userParams.criFilter; +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::calculateScanConvValues + */ +/*************************************************************************************************/ +void ScenGenCore::calculateScanConvValues() +{ + auto scenario = createScenario(); + + scenario->generate(); + + _softwareOutput.scanConversionProps = scenario->softwareOutput.scanConversionProps; + + delete scenario; +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::update zoom zone + */ +/*************************************************************************************************/ +void ScenGenCore::updateHDZoomGate(ScenGenZoomGate_t zoomGate) +{ + _userParams.minScanAx = zoomGate.startAxial; + _userParams.maxScanAx = zoomGate.endAxial; + _userParams.minScanAz = zoomGate.startAzimuth; + _userParams.maxScanAz = zoomGate.endAzimuth; + + process(); +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::calculateDtgcValues + */ +/*************************************************************************************************/ +void ScenGenCore::calculateDtgcValues() +{ + auto scenario = createScenario(); + + scenario->calcDtgcLut(); + + _hardwareOutput.hwRegister.dtgcLut = scenario->hardwareOuput.hwRegister.dtgcLut; + + delete scenario; +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::calculateStbValues + */ +/*************************************************************************************************/ +void ScenGenCore::calculateStbValues() +{ + _hardwareOutput.hwRegister.stbLut.clear(); + + for(auto i = _systemParams.mla - 2 * _systemParams.stb + 1; + i <= _systemParams.mla + 2 * _systemParams.stb - 1; i += 2) + { + _hardwareOutput.hwRegister.stbLut.push_back(i / 2 * _systemParams.mla); + } +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::calculateAoValues + */ +/*************************************************************************************************/ +void ScenGenCore::calculateAoValues() +{ + _hardwareOutput.hwRegister.ao = 64.2f / 99 * _userParams.aoB + (1.8f - (64.2f / 99)); +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::calculateLineFilterValues + */ +/*************************************************************************************************/ +void ScenGenCore::calculateLineFilterValues() +{ + _hardwareOutput.hwRegister.lineFilterLut = + QVector::fromList(_database.lineFilterLut[_userParams.lineFilter]); +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::calculateAtgcValues + */ +/*************************************************************************************************/ +void ScenGenCore::calculateAtgcValues() +{ + _hardwareOutput.hwRegister.atgcLut.clear(); + _hardwareOutput.hwRegister.atgcLut.append(_database.atgcB); + _hardwareOutput.hwRegister.atgcLut.append(_database.atgcD); + _hardwareOutput.hwRegister.atgcLut.append(_database.atgcPw); + _hardwareOutput.hwRegister.atgcLut.append(_database.atgcReserve); +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::calculateApodizationValues + */ +/*************************************************************************************************/ +void ScenGenCore::calculateApodizationValues() +{ + _hardwareOutput.hwRegister.apodizationLut.clear(); + _hardwareOutput.hwRegister.apodizationLut.append(_database.apodization1); + _hardwareOutput.hwRegister.apodizationLut.append(_database.apodization2); + _hardwareOutput.hwRegister.apodizationLut.append(_database.apodization3); + _hardwareOutput.hwRegister.apodizationLut.append(_database.apodization4); +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::calculateLpfValues + */ +/*************************************************************************************************/ +void ScenGenCore::calculateLpfValues() +{ + _hardwareOutput.hwRegister.lpfLut = QVector::fromList(_database.lpf); +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::updateRegs + */ +/*************************************************************************************************/ +void ScenGenCore::updateRegs() +{ + calculateStbValues(); + calculateAoValues(); + calculateLineFilterValues(); + calculateAtgcValues(); + calculateLpfValues(); + calculateApodizationValues(); +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::calcSecondaryProbeProps + */ +/*************************************************************************************************/ +void ScenGenCore::calcSecondaryProbeProps() +{ + auto angle = _userParams.angle; + auto virtualConvex = _userParams.virtualConvex; + auto c0 = _probeParams.getProbeProps().otiC0Values[_userParams.oti]; + auto dr = c0 * _systemParams.delayCalcDt; + + _probeParams.calcScndProps(dr, angle, virtualConvex); +} + +/*************************************************************************************************/ +/** + * @brief ScenGenCore::createScenario + * @return + */ +/*************************************************************************************************/ +BaseScenario* ScenGenCore::createScenario() +{ + if(_mode == EImageMode::B || _mode == EImageMode::BCri) + { + return new BModeScenario(_userParams, _systemParams, _probeParams); + } + else if(_mode == EImageMode::BM) + { + return new BmModeScenario(_userParams, _systemParams, _probeParams); + } + + return Q_NULLPTR; +} diff --git a/src/model/scenarioGenerator/core/general/Calculation.cpp b/src/model/scenarioGenerator/core/general/Calculation.cpp new file mode 100644 index 0000000..300c6ed --- /dev/null +++ b/src/model/scenarioGenerator/core/general/Calculation.cpp @@ -0,0 +1,449 @@ +#include "model/scenarioGenerator/core/general/Calculation.h" + +#include +#include + +#include "model/backendImageProcessor/core/algorithm/ScanConversionAlg.h" +#include "model/scenarioGenerator/core/general/AperturePosition.h" +#include "model/scenarioGenerator/core/general/BlendCoeff.h" + +/*************************************************************************************************/ +/** + * @brief Ctor + */ +/*************************************************************************************************/ +Calculation::Calculation() +{ +} + +/*************************************************************************************************/ +/** + * @brief Calculation::lag + * @param pulseTypeNo + * @param pulseProps + * @param impulseResponse + * @return + */ +/*************************************************************************************************/ +QVector Calculation::lag(int pulseTypeNo, + QList pulseProps, + QVector impulseResponse) +{ + QVector lag; + + for(auto i = 0; i < pulseTypeNo; i++) + { + auto excitationHalfPeriod = pulseProps[i].halfPeriod; + auto excitationHalfCycleNo = pulseProps[i].halfCycleNo; + QVector excitation; + for(auto j = 0U; j < excitationHalfCycleNo * excitationHalfPeriod; j++) + { + excitation.push_back(0); + } + + for(auto j = 0U; j < excitationHalfCycleNo; j++) + { + for(auto k = j * excitationHalfPeriod + 1; k <= (j + 1) * excitationHalfPeriod; k++) + { + excitation[k - 1] = powf(-1, j); + } + } + + auto pulseInverse = pulseProps[i].startPhase ? 1 : 0; + for(auto j = 0; j < excitation.length(); j++) + { + excitation[j] *= powf(-1, pulseInverse); + } + + auto oneWayIR = convolution(impulseResponse, excitation); + auto twoWayIR = convolution(oneWayIR, impulseResponse); + + auto maxIndex = 0U; + auto max = -1000.0f; + for(auto j = 0; j < twoWayIR.length(); j++) + { + if(twoWayIR[j] > max) + { + max = twoWayIR[j]; + maxIndex = j; + } + } + + lag.push_back(maxIndex + 1); + } + + return lag; +} + +/*************************************************************************************************/ +/** + * @brief Calculation::convolution + * @param input1 + * @param input2 + * @note Naming are borrowed from matlab, and yes, I know its bad + * @return + */ +/*************************************************************************************************/ +QVector Calculation::convolution(QVector input1, QVector input2) +{ + int m = input1.size(); + int n = input2.size(); + + QVector output; + for(auto i = 0; i < m + n - 1; i++) + { + output.push_back(0); + } + + for(auto i = 0; i < m + n - 1; i++) + { + auto max = qMax(0, i + 1 - n); + auto min = qMin(i, m - 1); + for(auto j = max; j <= min; j++) + { + output[i] += input1[j] * input2[i - j]; + } + } + + return output; +} + +/*************************************************************************************************/ +/** + * @brief Calculation::linearSpaceDistance + * @param interval + * @param distance + * @param maxSampleNo + * @return + */ +/*************************************************************************************************/ +QPair Calculation::linearSpaceDistance(float interval, + float distance, + quint32 maxSampleNo) +{ + quint32 sampleNo = 0; + float distanceOut = 0; + if(interval > 0) + { + sampleNo = ceil(interval / distance); + sampleNo = sampleNo > maxSampleNo ? maxSampleNo : sampleNo; + distanceOut = distance; + } + else + { + sampleNo = 1; + distanceOut = 0; + } + + return QPair(sampleNo, distanceOut); +} + +/*************************************************************************************************/ +/** + * @brief Calculation::linearSpaceInterval + * @param interval + * @param distance + * @param maxSampleNo + * @return + */ +/*************************************************************************************************/ +QPair Calculation::linearSpaceInterval(float interval, + float distance, + quint32 maxSampleNo) +{ + quint32 sampleNo = 0; + float distanceOut = 0; + if(interval > 0) + { + sampleNo = ceil(interval / distance); + sampleNo = sampleNo > maxSampleNo ? maxSampleNo : sampleNo; + distanceOut = interval / (sampleNo - 1); + } + else + { + sampleNo = 1; + distanceOut = 0; + } + + return QPair(sampleNo, distanceOut); +} + +/*************************************************************************************************/ +/** + * @brief Calculation::linearSpaceSampleNo + * @param interval + * @param distance + * @param maxSampleNo + * @return + */ +/*************************************************************************************************/ +QPair Calculation::linearSpaceSampleNo(float interval, + quint32 maxSampleNo) +{ + quint32 sampleNo = 0; + float distanceOut = 0; + if(interval > 0) + { + sampleNo = maxSampleNo; + distanceOut = interval / (sampleNo - 1); + } + else + { + sampleNo = 1; + distanceOut = 0; + } + + return QPair(sampleNo, + distanceOut); +} + +/*************************************************************************************************/ +/** + * @brief Calculation::linearSpace + * @param start + * @param end + * @param sampleNo + * @return + */ +/*************************************************************************************************/ +QVector Calculation::linearSpace(float start, float end, quint32 sampleNo) +{ + if(sampleNo == 1) + { + QVector temp; + temp.push_back(end); + + return temp; + } + + auto mul = end - start > 0 ? 1 : -1; + auto res = linearSpaceSampleNo(abs(end - start), sampleNo); + + auto dist = res.second * mul; + + QVector temp; + for(auto i = 0; i < res.first; i++) + { + temp.push_back(start + i * dist); + } + + return temp; +} + +/*************************************************************************************************/ +/** + * @brief Calculation::aperturePosition + * @param probe + * @param activeElementNo + * @param point + * @return + */ +/*************************************************************************************************/ +QPair, QVector > Calculation::aperturePosition( + ScenGenProbeParameters_t probe, + QVector activeElementNo, + QList points) +{ + Apertureposition ap; + + return ap.getAperturePosition(probe, activeElementNo, points); +} + +QVector > Calculation::blendCoeff(ScenGenUserParameters_t input, + ScenGenProbeParameters_t probe, + quint32 rxFocuspointNo, + float pointDax, + QList shotWeight) +{ + BlendCoeff bc; + + return bc.getBlendWeight(input, probe, rxFocuspointNo, pointDax, shotWeight); +} + +/*************************************************************************************************/ +/** + * @brief Calculation::qntzr + * @param data + * @param sign + * @param wordlength + * @param fractionalLength + * @param maxLevel + * @param integerOutput + * @param enable + * @param round + * @return + */ +/*************************************************************************************************/ +QVector Calculation::qntzr(QVector data, + quint32 sign, + quint32 wordLength, + quint32 fractionalLength, + float maxLevel, + bool integerOutput, + bool useRound, + bool twosCmpl) + +{ + auto fullScale = + powf(2.0f, wordLength - fractionalLength - sign) - 1 + + (powf(2.0f, fractionalLength) - 1) / + powf(2.0f, fractionalLength); + if(maxLevel > 0) + { + if(fractionalLength > 0) + { + for(auto i = 0; i < data.length(); i++) + { + data[i] /= maxLevel; + } + } + else + { + fullScale = maxLevel; + } + } + + for(auto i = 0; i < data.length(); i++) + { + if(data[i] > fullScale) + { + data[i] = fullScale; + } + + if(data[i] < -fullScale) + { + data[i] = -fullScale; + } + } + + QVector output; + if(integerOutput) + { + for(auto i = 0; i < data.length(); i++) + { + float out; + if(useRound) + { + out = + static_cast(roundf(data[i] / fullScale * + (powf(2.0f, wordLength - sign) - 1))); + } + else + { + out = + static_cast(floorf(data[i] / fullScale * + (powf(2.0f, wordLength - sign) - 1))); + } + if(out < 0) + { + out += powf(2.0f, wordLength); + } + + output.push_back(out); + } + } + else + { + for(auto i = 0; i < data.length(); i++) + { + quint32 out; + if(useRound) + { + out = + static_cast(roundf(data[i] / fullScale * + (powf(2.0f, wordLength - sign) - 1)) / + (fullScale * (powf(2.0f, wordLength - sign) - 1))); + } + else + { + out = + static_cast(floorf(data[i] / fullScale * + (powf(2.0f, wordLength - sign) - 1)) / + (fullScale * (powf(2.0f, wordLength - sign) - 1))); + } + + output.push_back(out); + } + } + + return output; +} + +/*************************************************************************************************/ +/** + * @brief Calculation::calcDtgcLut + * @param dtgcSlider + * @param dtgcLen + * @param maxWeight + * @return + */ +/*************************************************************************************************/ +QVector Calculation::calcDtgcLut(QList dtgcSlider, float dtgcLen, float maxWeight) +{ + QVector dtgcLut; + + for(auto i = 0; i < 1024; i++) + { + dtgcLut.push_back(0); + } + + auto startDepthIndex = 1; + auto sliderNo = dtgcSlider.length() - 1; + + for(auto i = 0; i < sliderNo; i++) + { + for(auto j = startDepthIndex; j <= roundf((i + 1) * dtgcLen / sliderNo); j++) + { + auto temp = (j - startDepthIndex) * (dtgcSlider[i + 1] - dtgcSlider[i]) / roundf( + dtgcLen / sliderNo) + dtgcSlider[i]; + + dtgcLut[j - 1] = powf(maxWeight, (temp - 50) / 50); + } + startDepthIndex = roundf((i + 1) * dtgcLen / sliderNo) + 1; + } + + return dtgcLut; +} + +/*************************************************************************************************/ +/** + * + */ +/*************************************************************************************************/ +//template +//QVector Calculation::repElem(QVector input, quint32 number) +//{ + +//} + +/*************************************************************************************************/ +/** + * + */ +/*************************************************************************************************/ +//template +//QVector Calculation::repMat(QVector input, quint32 number) +//{ +//} + +/*************************************************************************************************/ +/** + * + */ +/*************************************************************************************************/ +//template +//QVector Calculation::zeros(quint32 length) +//{ + +//} + +/*************************************************************************************************/ +/** + * + */ +/*************************************************************************************************/ +//template +//QVector Calculation::ones(quint32 length) +//{ + +//} diff --git a/src/model/scenarioGenerator/core/scenario/B/BModeScenario.cpp b/src/model/scenarioGenerator/core/scenario/B/BModeScenario.cpp new file mode 100644 index 0000000..7f8368d --- /dev/null +++ b/src/model/scenarioGenerator/core/scenario/B/BModeScenario.cpp @@ -0,0 +1,270 @@ +#include "model/scenarioGenerator/core/scenario/B/BModeScenario.h" + +#include "model/scenarioGenerator/core/general/Calculation.h" +#include "model/scenarioGenerator/core/scenario/type/frame/BFrame.h" + +BModeScenario::BModeScenario(ScenGenUserParameters_t userParam, + ScenGenSystemParameters_t sysParam, + ScenGenProbeParameters_t probeParam) : + BaseScenario(userParam, sysParam, probeParam) +{ + _compoundModeNumber = 1; +} + +/*************************************************************************************************/ +void BModeScenario::initRegisterSpace() +{ +} + +/*************************************************************************************************/ +void BModeScenario::calcFrameParameters() +{ + frameParams.clear(); + for(auto i = 0; i < compoundFrameNumber; i++) + { + auto frame = new BFrame(userParams, sysParams, probeParams); + frame->setParameters(i); + frameParams.append(frame); + } +} + +/*************************************************************************************************/ +void BModeScenario::calcPulseIntervalFrameRate() +{ + float frameTimeSum = 0; + quint32 totalShotNumber = 0; + + QVector sramPulseInterval = Calculation::zeros(hardwareOuput.focusTypeNumber); + + int start = 1; + for(auto i = 0; i < _compoundModeNumber; i++) + { + auto focusTypeNumber = frameParams[i]->focusTypeNumber; + auto pulseInterval = frameParams[i]->pulseInterval; + for(auto j = start; j <= start + focusTypeNumber - 1; j++) + { + sramPulseInterval[j - 1] = ceilf(pulseInterval / sysParams.fpgaTxDt); + } + start += focusTypeNumber; + + auto shotNumber = frameParams[i]->txShotNumber; + frameTimeSum += pulseInterval * shotNumber; + totalShotNumber += shotNumber; + } + + hardwareOuput.pulseInterval = sramPulseInterval; + hardwareOuput.totalTxShotNumber = totalShotNumber; + softwareOutput.scenarioDependent.frameRate = 1 / frameTimeSum; +} + +/*************************************************************************************************/ +void BModeScenario::calcIndexParameters() +{ + hardwareOuput.indexParams.pulsePropertiesIndex.clear(); + hardwareOuput.indexParams.receiverConfigurationIndex.clear(); + hardwareOuput.indexParams.shotPropertiesIndex.clear(); + hardwareOuput.indexParams.firstLineInFrame.clear(); + hardwareOuput.indexParams.lastLineInFrame.clear(); + hardwareOuput.indexParams.dLineNum.clear(); + hardwareOuput.indexParams.dEnsembleNum.clear(); + + auto criFrameNumber = softwareOutput.scenarioDependent.criFrameNumber; + auto frameLineNumber = frameParams[0]->txLineNumber * criFrameNumber; + auto frameFocusLineNumber = frameLineNumber * userParams.focusNumber; + + if(userParams.focusFrequencyCompound) + { + hardwareOuput.indexParams.pulsePropertiesIndex = + Calculation::repMat({1, 2}, frameLineNumber); + hardwareOuput.indexParams.receiverConfigurationIndex = + Calculation::repMat({1, 2}, frameLineNumber); + } + else if(userParams.pulseInversion) + { + hardwareOuput.indexParams.pulsePropertiesIndex = + Calculation::repMat({1, 2}, frameFocusLineNumber); + hardwareOuput.indexParams.receiverConfigurationIndex = + Calculation::ones(2 * frameFocusLineNumber); + } + else + { + hardwareOuput.indexParams.pulsePropertiesIndex = + Calculation::ones(frameFocusLineNumber); + hardwareOuput.indexParams.receiverConfigurationIndex = + Calculation::ones(frameFocusLineNumber); + } + + auto repeatNum = userParams.pulseInversion ? 2U : 1U; + QVector temp; + for(auto i = 1U; i <= frameFocusLineNumber; i++) + { + temp.push_back(i); + } + hardwareOuput.indexParams.shotPropertiesIndex = Calculation::repElem(temp, repeatNum); + + auto totalTxShotNumber = hardwareOuput.totalTxShotNumber; + auto frameShotNumber = totalTxShotNumber / criFrameNumber; + + hardwareOuput.indexParams.firstLineInFrame.append(Calculation::ones(1)); + hardwareOuput.indexParams.firstLineInFrame.append( + Calculation::zeros(frameShotNumber - 1)); + + hardwareOuput.indexParams.firstLineInFrame = + Calculation::repMat(hardwareOuput.indexParams.firstLineInFrame, criFrameNumber); + + hardwareOuput.indexParams.lastLineInFrame.append( + Calculation::zeros(frameShotNumber - 1)); + hardwareOuput.indexParams.lastLineInFrame.append(Calculation::ones(1)); + + hardwareOuput.indexParams.lastLineInFrame = + Calculation::repMat(hardwareOuput.indexParams.lastLineInFrame, criFrameNumber); + + hardwareOuput.indexParams.dLineNum = Calculation::zeros(totalTxShotNumber); + hardwareOuput.indexParams.dEnsembleNum = Calculation::zeros(totalTxShotNumber); +} + +/*************************************************************************************************/ +void BModeScenario::calcPulseProperties() +{ + hardwareOuput.hwRegister.pulseProps.clear(); + + quint8 pulseTypeNo; + + if(userParams.focusFrequencyCompound) + { + pulseTypeNo = 2; + for(auto i = 0; i < pulseTypeNo; i++) + { + Pulse_t temp; + temp.halfPeriod = frameParams[0]->halfPeriod[i]; + temp.halfCycleNo = probeParams.getProbeProps().ffcHalfCycleNoValues; + temp.pulseVoltSel = false; + temp.startPhase = false; + temp.dampingPulseWidth = 0; + hardwareOuput.hwRegister.pulseProps.append(temp); + } + } + else if(userParams.pulseInversion) + { + pulseTypeNo = 2; + for(auto i = 0; i < pulseTypeNo; i++) + { + Pulse_t temp; + temp.halfPeriod = frameParams[0]->halfPeriod[0]; + temp.halfCycleNo = + probeParams.getProbeProps().hiHalfCycleNoValues[userParams.frequency]; + temp.pulseVoltSel = false; + temp.startPhase = i == 1; + temp.dampingPulseWidth = 0; + hardwareOuput.hwRegister.pulseProps.append(temp); + } + } + else + { + pulseTypeNo = 1; + Pulse_t temp; + temp.halfPeriod = frameParams[0]->halfPeriod[0]; + if(userParams.harmonicImaging) + { + temp.halfCycleNo = + probeParams.getProbeProps().hiHalfCycleNoValues[userParams.frequency]; + } + else + { + temp.halfCycleNo = probeParams.getProbeProps().halfCycleNoValues; + } + temp.pulseVoltSel = false; + temp.startPhase = false; + temp.dampingPulseWidth = 0; + hardwareOuput.hwRegister.pulseProps.append(temp); + } + + hardwareOuput.hwRegister.pulseTypeNumber = pulseTypeNo; +} + +/*************************************************************************************************/ +void BModeScenario::calcRxBeamFormerProperties() +{ + hardwareOuput.hwRegister.rxBeamFormerProps.clear(); + + auto fpgaTxDt = sysParams.fpgaTxDt; + auto delayCalcDt = sysParams.delayCalcDt; + auto apodizationSel = sysParams.apodization; + auto rxBeamFormerTypeNumber = 0; + + if(userParams.focusFrequencyCompound || userParams.pulseInversion) + { + rxBeamFormerTypeNumber = 2; + } + else + { + rxBeamFormerTypeNumber = 1; + } + + auto lag = Calculation::lag(rxBeamFormerTypeNumber, + hardwareOuput.hwRegister.pulseProps, + probeParams.getProbeProps().impulseResponse); + + for(auto i = 0; i < rxBeamFormerTypeNumber; i++) + { + RxBeamFormer_t temp; + temp.mla = frameParams[0]->rxBeamFormerNumber; + temp.apodizationSel = apodizationSel; + temp.lag = std::roundf(lag[i] * fpgaTxDt / delayCalcDt); + hardwareOuput.hwRegister.rxBeamFormerProps.append(temp); + } + + hardwareOuput.hwRegister.rxBeamFormerTypeNumber = rxBeamFormerTypeNumber; +} + +/*************************************************************************************************/ +void BModeScenario::calcReceiverConfigProperties() +{ + hardwareOuput.hwRegister.receiverConfigProps.clear(); + + auto receiverConfigTypeNumber = 0; + + if(userParams.focusFrequencyCompound) + { + receiverConfigTypeNumber = 2; + } + else + { + receiverConfigTypeNumber = 1; + } + + for(auto i = 0; i < receiverConfigTypeNumber; i++) + { + ReceiverConfig_t temp; + temp.mla = frameParams[0]->mla; + temp.lineMode = 1; + temp.aTgcSel = 1; + temp.stbEn = true; + temp.stb = frameParams[0]->stb; + temp.subtractFilterEn = userParams.pulseInversion; + temp.dcCancelEn = true; + if(userParams.focusFrequencyCompound) + { + temp.ncoFreqSel = i + 1; + } + else + { + temp.ncoFreqSel = 1; + } + + temp.lpfSel = 1; + temp.absEn = true; + temp.focusNo = frameParams[0]->focusNumber; + temp.lineFilterEn = true; + temp.ddcn = true; + hardwareOuput.hwRegister.receiverConfigProps.append(temp); + } + + hardwareOuput.hwRegister.receiverConfigTypeNumber = receiverConfigTypeNumber; +} + +/*************************************************************************************************/ +void BModeScenario::calcFreqLut() +{ + hardwareOuput.hwRegister.freqLut = frameParams[0]->f0; +} diff --git a/src/model/scenarioGenerator/core/scenario/BaseScenario.cpp b/src/model/scenarioGenerator/core/scenario/BaseScenario.cpp new file mode 100644 index 0000000..930801a --- /dev/null +++ b/src/model/scenarioGenerator/core/scenario/BaseScenario.cpp @@ -0,0 +1,278 @@ +#include "model/scenarioGenerator/core/scenario/BaseScenario.h" + +#include "model/scenarioGenerator/core/general/BlendCoeff.h" +#include "model/scenarioGenerator/core/general/Calculation.h" + +void BaseScenario::calcCriFrameNo() +{ + softwareOutput.scenarioDependent.criFrameNumber = + probeParams.getProbeProps().criSteeringAngles[userParams.cri].length(); +} + +/*************************************************************************************************/ +void BaseScenario::calcCompoundFrameNo() +{ + auto criFrameNo = softwareOutput.scenarioDependent.criFrameNumber; + compoundFrameNumber = criFrameNo + _compoundModeNumber - 1; +} + +/*************************************************************************************************/ +void BaseScenario::calcTotalFocusTypeNumber() +{ + quint32 temp = 0; + + for(auto i = 0; i < compoundFrameNumber; i++) + { + temp += frameParams[i]->focusTypeNumber; + } + + hardwareOuput.focusTypeNumber = temp; +} + +/*************************************************************************************************/ +void BaseScenario::calcTxRxParameters() +{ + hardwareOuput.txParams.clear(); + hardwareOuput.rxParams.clear(); + + hardwareOuput.rxBeamFormerNumber = 0; + + for(auto i = 0; i < compoundFrameNumber; i++) + { + auto frameParam = frameParams[i]; + + hardwareOuput.txParams.txActiveElementNumber.append( + frameParam->txAperture.activeElementNumber); + + hardwareOuput.txParams.txStartActiveElementNumber.append( + frameParam->txAperture.startActiveElementNumber); + + hardwareOuput.txParams.minDelay.append(frameParam->delay.minDelay); + hardwareOuput.txParams.maxDelay.append(frameParam->delay.maxDelay); + hardwareOuput.txParams.maxDelayQ.append(frameParam->delay.maxDelayQ); + for(auto j = 0; j < frameParam->focusPoint.length(); j++) + { + hardwareOuput.txParams.txFocusXPos.append(frameParam->focusPoint[j].x); + hardwareOuput.txParams.txFocusYPos.append(frameParam->focusPoint[j].y); + hardwareOuput.txParams.txFocusZPos.append(frameParam->focusPoint[j].z); + } + + for(auto j = 0; j < frameParam->txInterceptPoint.length(); j++) + { + hardwareOuput.txParams.interceptXPos.append(frameParam->txInterceptPoint[j].x); + hardwareOuput.txParams.interceptYPos.append(frameParam->txInterceptPoint[j].y); + hardwareOuput.txParams.interceptZPos.append(frameParam->txInterceptPoint[j].z); + hardwareOuput.rxParams.interceptXPos.append(frameParam->rxInterceptPoint[j].x); + hardwareOuput.rxParams.interceptYPos.append(frameParam->rxInterceptPoint[j].y); + hardwareOuput.rxParams.interceptZPos.append(frameParam->rxInterceptPoint[j].z); + } + + for(auto j = 0; j < frameParam->r0Point.length(); j++) + { + hardwareOuput.rxParams.thetaSin.append(sin(frameParam->r0Point[j].theta)); + hardwareOuput.rxParams.thetaCos.append(cos(frameParam->r0Point[j].theta)); + hardwareOuput.rxParams.r0XPosition.append(frameParam->r0Point[j].x); + hardwareOuput.rxParams.r0YPosition.append(frameParam->r0Point[j].y); + hardwareOuput.rxParams.r0ZPosition.append(frameParam->r0Point[j].z); + } + + hardwareOuput.rxParams.rxFocusPointNumber.append( + Calculation::repElem({frameParam->rxFocusPointNumber}, + frameParam->focusTypeNumber)); + + hardwareOuput.rxParams.r0Position.append( + Calculation::repElem({frameParam->minScanAx / frameParam->dR}, + frameParam->focusTypeNumber)); + + hardwareOuput.rxParams.rxActiveElementStep.append(frameParam->rxActiveElementStep); + hardwareOuput.rxParams.interceptPointFiringTime.append(frameParam->interceptPointFiringTime); + + hardwareOuput.rxParams.phiSin.append(Calculation::zeros(frameParam-> + rxBeamFormerNumber * + frameParam->focusTypeNumber)); + hardwareOuput.rxParams.phiCos.append(Calculation::ones(frameParam-> + rxBeamFormerNumber * + frameParam->focusTypeNumber)); + + hardwareOuput.rxParams.rxR0MinDelay.append(frameParam->delay.rxR0MinDelay); + hardwareOuput.rxParams.rxR0MaxDelay.append(frameParam->delay.rxR0MaxDelay); + + hardwareOuput.rxParams.rxR0MinDelayQ.append(frameParam->delay.rxR0MinDelayQ); + hardwareOuput.rxParams.rxR0MaxDelayQ.append(frameParam->delay.rxR0MaxDelayQ); + + hardwareOuput.rxParams.rxR0ActiveElementNumber.append( + frameParam->rxAperture.activeElementNumber); + + hardwareOuput.rxParams.rxR0CenterActiveElementNumber.append( + frameParam->rxAperture.centerActiveElementNumber); + + hardwareOuput.rxParams.rxR0StartActiveElementNumber.append( + frameParam->rxAperture.startActiveElementNumber); + + hardwareOuput.rxParams.txR0MinDelay.append(frameParam->delay.txR0MinDelay); + hardwareOuput.rxParams.txR0MinDelayQ.append(frameParam->delay.txR0MinDelayQ); + + if(frameParam->rxBeamFormerNumber > hardwareOuput.rxBeamFormerNumber) + { + hardwareOuput.rxBeamFormerNumber = frameParam->rxBeamFormerNumber; + } + } +} + +/*************************************************************************************************/ +void BaseScenario::calcDtgcLut() +{ + if(frameParams.length() == 0) + { + return; + } + + auto dtgcSlider = userParams.dtgc; + auto dtgcLen = ceilf(frameParams[0]->rxFocusPointNumber / 8.0f); + auto maxWeight = sysParams.dtgcMaxWeight; + + hardwareOuput.hwRegister.dtgcLut = calcDtgcLut(dtgcSlider, dtgcLen, maxWeight); +} + +/*************************************************************************************************/ +QVector BaseScenario::calcDtgcLut(QList dtgcSlider, float dtgcLen, float maxWeight) +{ + QVector dtgcLut; + + for(auto i = 0; i < 1024; i++) + { + dtgcLut.push_back(0); + } + + auto startDepthIndex = 1; + auto sliderNo = dtgcSlider.length() - 1; + + for(auto i = 0; i < sliderNo; i++) + { + for(auto j = startDepthIndex; j <= roundf((i + 1) * dtgcLen / sliderNo); j++) + { + auto temp = (j - startDepthIndex) * (dtgcSlider[i + 1] - dtgcSlider[i]) / roundf( + dtgcLen / sliderNo) + dtgcSlider[i]; + + dtgcLut[j - 1] = powf(maxWeight, (temp - 50) / 50); + } + startDepthIndex = roundf((i + 1) * dtgcLen / sliderNo) + 1; + } + + return dtgcLut; +} + +/*************************************************************************************************/ +void BaseScenario::calcBlendLut() +{ + auto shotWeight = sysParams.blendShotWeight; + auto rxFocusPointNumber = frameParams[0]->rxFocusPointNumber; + auto rxPointDax = frameParams[0]->rxPointDax; + + BlendCoeff bc; + hardwareOuput.hwRegister.blendWeight = bc.getBlendWeight(userParams, + probeParams, + rxFocusPointNumber, + rxPointDax, + shotWeight); +} + +/*************************************************************************************************/ +void BaseScenario::calcElementPositionLut() +{ + hardwareOuput.hwRegister.elementXPosition = + probeParams.getScndProbeProps().elementXPosition; + + hardwareOuput.hwRegister.elementYPosition = + probeParams.getScndProbeProps().elementYPosition; + + hardwareOuput.hwRegister.elementZPosition = + probeParams.getScndProbeProps().elementZPosition; +} + +/*************************************************************************************************/ +void BaseScenario::calcScenarioIndexRegisters() +{ + hardwareOuput.hwRegister.scenarioStartIndex = 0; + hardwareOuput.hwRegister.scenarioEndIndex = hardwareOuput.focusTypeNumber - 1; +} + +/*************************************************************************************************/ +void BaseScenario::calcScanConversionParameters() +{ + softwareOutput.scanConversionProps.clear(); + + for(auto i = 0; i < _compoundModeNumber; i++) + { + ScenGenScanConversionConfig_t temp; + temp.linear = probeParams.getProbeProps().linear; + temp.probeRadius = probeParams.getProbeProps().radius; + temp.fieldOfView = probeParams.getScndProbeProps().fieldOfView; + temp.probeFieldOfView = probeParams.getProbeProps().fieldOfView; + temp.virtualOriginalZ = probeParams.getScndProbeProps().virtualOriginalZ; + temp.bMinScanAx = sysParams.startDepth; + temp.bMinScanAz = -probeParams.getScndProbeProps().fieldOfView / 2; + temp.bMaxScanAx = userParams.depth; + temp.bMaxScanAz = probeParams.getScndProbeProps().fieldOfView / 2; + temp.minScanAx = frameParams[i]->minScanAx; + temp.minScanAz = frameParams[i]->minScanAz; + temp.maxScanAx = frameParams[i]->maxScanAx; + temp.steering = frameParams[i]->steering; + temp.rxLineNo = frameParams[i]->rxLineNumber; + temp.rxFocusPointNo = frameParams[i]->rxFocusPointNumber; + temp.rxLineDaz = frameParams[i]->rxLineDaz; + temp.rxPointDax = frameParams[i]->rxPointDax; + temp.virtualConvex = userParams.virtualConvex; + temp.vcMaxTheta = probeParams.getScndProbeProps().vcMaxTheta; + temp.angle = userParams.angle; + temp.calcPixelParams(userParams.X, userParams.Z, + userParams.hdZoom); + + softwareOutput.scanConversionProps.append(temp); + } +} + +/*************************************************************************************************/ +BaseScenario::BaseScenario(ScenGenUserParameters_t userParams, + ScenGenSystemParameters_t sysParams, + ScenGenProbeParameters_t probeParams) +{ + this->userParams = userParams; + this->sysParams = sysParams; + this->probeParams = probeParams; +} + +/*************************************************************************************************/ +void BaseScenario::calcSecondaryProbeParameters() +{ + auto angle = userParams.angle; + auto virtualConvex = userParams.virtualConvex; + auto c0 = probeParams.getProbeProps().otiC0Values[userParams.oti]; + auto dr = c0 * sysParams.delayCalcDt; + + probeParams.calcScndProps(dr, angle, virtualConvex); +} + +/*************************************************************************************************/ +void BaseScenario::generate() +{ + calcCriFrameNo(); + calcCompoundFrameNo(); + calcFrameParameters(); + calcTotalFocusTypeNumber(); + + calcPulseIntervalFrameRate(); + calcTxRxParameters(); + calcIndexParameters(); + + calcPulseProperties(); + calcRxBeamFormerProperties(); + calcReceiverConfigProperties(); + calcDtgcLut(); + calcBlendLut(); + calcFreqLut(); + calcElementPositionLut(); + calcScenarioIndexRegisters(); + + calcScanConversionParameters(); +} diff --git a/src/model/scenarioGenerator/core/scenario/Bm/BmModeScenario.cpp b/src/model/scenarioGenerator/core/scenario/Bm/BmModeScenario.cpp new file mode 100644 index 0000000..966ca2e --- /dev/null +++ b/src/model/scenarioGenerator/core/scenario/Bm/BmModeScenario.cpp @@ -0,0 +1,436 @@ +#include "model/scenarioGenerator/core/scenario/Bm/BmModeScenario.h" + +#include "model/scenarioGenerator/core/general/Calculation.h" +#include "model/scenarioGenerator/core/scenario/type/frame/MFrame.h" +#include "model/scenarioGenerator/core/scenario/type/frame/BFrame.h" + +BmModeScenario::BmModeScenario(ScenGenUserParameters_t userParam, + ScenGenSystemParameters_t sysParam, + ScenGenProbeParameters_t probeParam) : + BaseScenario(userParam, sysParam, probeParam) +{ +} + +/*************************************************************************************************/ +void BmModeScenario::initRegisterSpace() +{ +} + +/*************************************************************************************************/ +void BmModeScenario::calcFrameParameters() +{ + for(auto i = 0; i < frameParams.length(); i++) + { + delete frameParams[i]; + } + + frameParams.clear(); + + auto mFrame = new MFrame(userParams, sysParams, probeParams); + mFrame->setParameters(0); + frameParams.append(mFrame); + + auto bFrame = new BFrame(userParams, sysParams, probeParams); + bFrame->setParameters(0); + frameParams.append(bFrame); +} + +/*************************************************************************************************/ +void BmModeScenario::calcPulseIntervalFrameRate() +{ + auto pulseInverse = userParams.pulseInversion ? 1U : 0U; + auto bTxShotNumber = frameParams[1]->txShotNumber; + auto b2bPulseInterval = frameParams[1]->pulseInterval; + auto probeMLinesPri = probeParams.getProbeProps().mLinesPri; + mLinesPri = probeMLinesPri * (pulseInverse + 1); + bmRatio = + static_cast((floorf(probeMLinesPri / b2bPulseInterval) - 1) * (pulseInverse + 1)); + mLineNumber = ceil(bTxShotNumber / bmRatio); + bRemPulseNumber = bTxShotNumber % bmRatio; + b2mPulseInterval = mLinesPri - (bmRatio + pulseInverse) * b2bPulseInterval; + mTxShotNumber = mLineNumber * (pulseInverse + 1); + auto fpgaTxDt = sysParams.fpgaTxDt; + + QVector sramPulseInterval; + + if(bRemPulseNumber > 0) + { + sramPulseInterval.push_back(b2bPulseInterval); + QVector temp = Calculation::ones(bmRatio / (pulseInverse + 1) - 1); + for(auto i = 0; i < temp.length(); i++) + { + temp[i] *= b2bPulseInterval; + } + temp.push_back(b2mPulseInterval); + temp = Calculation::repMat(temp, mLineNumber - 1); + + sramPulseInterval.append(temp); + + temp = Calculation::ones(bRemPulseNumber - 1); + for(auto i = 0; i < temp.length(); i++) + { + temp[i] *= b2bPulseInterval; + } + + sramPulseInterval.append(temp); + + sramPulseInterval.push_back(mLinesPri - (bRemPulseNumber + pulseInverse) * + b2bPulseInterval); + } + else + { + sramPulseInterval.push_back(b2bPulseInterval); + QVector temp = Calculation::ones(bmRatio / (pulseInverse + 1) - 1); + for(auto i = 0; i < temp.length(); i++) + { + temp[i] *= b2bPulseInterval; + } + temp.push_back(b2mPulseInterval); + temp = Calculation::repMat(temp, mLineNumber); + + sramPulseInterval.append(temp); + } + + hardwareOuput.pulseInterval.clear(); + for(auto i = 0; i < sramPulseInterval.length(); i++) + { + hardwareOuput.pulseInterval.append(sramPulseInterval[i] / fpgaTxDt); + } + + softwareOutput.scenarioDependent.frameRate = 1 / (mLineNumber * mLinesPri); + + hardwareOuput.totalTxShotNumber = bTxShotNumber + mTxShotNumber; +} + +/*************************************************************************************************/ +void BmModeScenario::calcIndexParameters() +{ + auto pulseInverse = (userParams.pulseInversion ? 1 : 0) + 1; + auto bTxLineNumber = frameParams[1]->txLineNumber; + auto bTxShotNumber = frameParams[1]->txShotNumber; + + auto totalTxShotNumber = hardwareOuput.totalTxShotNumber; + + QVector mTxIndexMask; + + if(pulseInverse == 2) + { + if(bRemPulseNumber > 0) + { + QVector temp = Calculation::repMat({1, 2}, bmRatio / 2); + QVector temp2 = {3, 4}; + temp2.append(temp); + + temp = Calculation::repMat(temp2, mLineNumber - 1); + temp.append({3, 4}); + + temp2 = Calculation::repMat({1, 2}, bRemPulseNumber / 2); + temp.append(temp2); + + hardwareOuput.indexParams.pulsePropertiesIndex = temp; + + temp.clear(); + for(auto i = 0; i < pulseInverse; i++) + { + temp.push_back(2); + } + + temp.append(Calculation::ones(bmRatio)); + + temp = Calculation::repMat(temp, mLineNumber - 1); + + for(auto i = 0; i < pulseInverse; i++) + { + temp.push_back(2); + } + + temp.append(Calculation::ones(bRemPulseNumber)); + + hardwareOuput.indexParams.receiverConfigurationIndex = temp; + + mTxIndexMask.append({true, true}); + for(auto i = 0; i < bmRatio; i++) + { + mTxIndexMask.append(false); + } + + mTxIndexMask = Calculation::repMat(mTxIndexMask, mLineNumber - 1); + + mTxIndexMask.append({true, true}); + for(auto i = 0; i < bRemPulseNumber; i++) + { + mTxIndexMask.append(false); + } + } + else + { + QVector temp = Calculation::repMat({1, 2}, bmRatio / 2); + QVector temp2 = {3, 4}; + temp2.append(temp); + + temp = Calculation::repMat(temp2, mLineNumber); + + hardwareOuput.indexParams.pulsePropertiesIndex = temp; + + temp.clear(); + for(auto i = 0; i < pulseInverse; i++) + { + temp.push_back(2); + } + + temp.append(Calculation::ones(bmRatio)); + + temp = Calculation::repMat(temp, mLineNumber); + + hardwareOuput.indexParams.receiverConfigurationIndex = temp; + + mTxIndexMask.append({true, true}); + for(auto i = 0; i < bmRatio; i++) + { + mTxIndexMask.append(false); + } + + mTxIndexMask = Calculation::repMat(mTxIndexMask, mLineNumber); + } + } + else + { + if(bRemPulseNumber > 0) + { + QVector temp = {2}; + temp.append(Calculation::ones(bmRatio)); + temp = Calculation::repMat(temp, mLineNumber - 1); + temp.push_back(2); + temp.append(Calculation::ones(bRemPulseNumber)); + + hardwareOuput.indexParams.pulsePropertiesIndex = temp; + + temp.clear(); + for(auto i = 0; i < pulseInverse; i++) + { + temp.push_back(2); + } + temp.append(Calculation::ones(bmRatio)); + temp = Calculation::repMat(temp, mLineNumber - 1); + for(auto i = 0; i < pulseInverse; i++) + { + temp.push_back(2); + } + + temp.append(Calculation::ones(bRemPulseNumber)); + + hardwareOuput.indexParams.receiverConfigurationIndex = temp; + + mTxIndexMask.append({true}); + for(auto i = 0; i < bmRatio; i++) + { + mTxIndexMask.append(false); + } + + mTxIndexMask = Calculation::repMat(mTxIndexMask, mLineNumber - 1); + mTxIndexMask.push_back(true); + + for(auto i = 0; i < bRemPulseNumber; i++) + { + mTxIndexMask.append(false); + } + } + else + { + QVector temp = {2}; + temp.append(Calculation::ones(bmRatio)); + temp = Calculation::repMat(temp, mLineNumber); + + hardwareOuput.indexParams.pulsePropertiesIndex = temp; + + temp.clear(); + for(auto i = 0; i < pulseInverse; i++) + { + temp.push_back(2); + } + temp.append(Calculation::ones(bmRatio)); + temp = Calculation::repMat(temp, mLineNumber); + + hardwareOuput.indexParams.receiverConfigurationIndex = temp; + + mTxIndexMask.append({true}); + for(auto i = 0; i < bmRatio; i++) + { + mTxIndexMask.append(false); + } + + mTxIndexMask = Calculation::repMat(mTxIndexMask, mLineNumber); + } + } + + hardwareOuput.indexParams.shotPropertiesIndex.clear(); + hardwareOuput.indexParams.firstLineInFrame.clear(); + hardwareOuput.indexParams.lastLineInFrame.clear(); + + hardwareOuput.indexParams.firstLineInFrame.push_back(true); + + for(auto i = 0; i < mTxIndexMask.length(); i++) + { + if(mTxIndexMask[i]) + { + hardwareOuput.indexParams.shotPropertiesIndex.push_back(1); + hardwareOuput.indexParams.firstLineInFrame.push_back(false); + hardwareOuput.indexParams.lastLineInFrame.push_back(false); + } + else + { + QVector temp; + for(auto i = 0; i < bTxLineNumber; i++) + { + temp.push_back(2 + i); + } + hardwareOuput.indexParams.shotPropertiesIndex.append( + Calculation::repElem(temp, pulseInverse)); + + hardwareOuput.indexParams.firstLineInFrame.append(true); + hardwareOuput.indexParams.firstLineInFrame.append( + Calculation::repElem({false}, bTxShotNumber - 1)); + + hardwareOuput.indexParams.lastLineInFrame.append( + Calculation::repElem({false}, bTxShotNumber - 1)); + hardwareOuput.indexParams.lastLineInFrame.append(true); + } + } + + hardwareOuput.indexParams.dLineNum = Calculation::zeros(totalTxShotNumber); + hardwareOuput.indexParams.dEnsembleNum = Calculation::zeros(totalTxShotNumber); +} + +/*************************************************************************************************/ +void BmModeScenario::calcPulseProperties() +{ + quint32 pulseTypeNumber; + + hardwareOuput.hwRegister.pulseProps.clear(); + + if(userParams.pulseInversion) + { + pulseTypeNumber = 4; + for(auto i = 0; i < pulseTypeNumber; i++) + { + Pulse_t pulse; + pulse.startPhase = i % 2 == 1; + pulse.halfPeriod = frameParams[0]->halfPeriod[0]; + pulse.halfCycleNo = + probeParams.getProbeProps().hiHalfCycleNoValues[userParams.frequency]; + pulse.pulseVoltSel = false; + pulse.dampingPulseWidth = 0; + + hardwareOuput.hwRegister.pulseProps.append(pulse); + } + } + else + { + pulseTypeNumber = 2; + for(auto i = 0; i < pulseTypeNumber; i++) + { + Pulse_t pulse; + pulse.startPhase = false; + pulse.halfPeriod = frameParams[0]->halfPeriod[0]; + if(userParams.harmonicImaging) + { + pulse.halfCycleNo = + probeParams.getProbeProps().hiHalfCycleNoValues[userParams.frequency]; + } + else + { + pulse.halfCycleNo = probeParams.getProbeProps().halfCycleNoValues; + } + pulse.pulseVoltSel = false; + pulse.dampingPulseWidth = 0; + + hardwareOuput.hwRegister.pulseProps.append(pulse); + } + } + + hardwareOuput.hwRegister.pulseTypeNumber = pulseTypeNumber; +} + +/*************************************************************************************************/ +void BmModeScenario::calcRxBeamFormerProperties() +{ + hardwareOuput.hwRegister.rxBeamFormerProps.clear(); + + auto fpgaTxDt = sysParams.fpgaTxDt; + auto delayCalcDt = sysParams.delayCalcDt; + auto apodizationSel = sysParams.apodization; + auto rxBeamFormerTypeNumber = 0; + + QVector mlaVals; + + if(userParams.pulseInversion) + { + rxBeamFormerTypeNumber = 4; + + mlaVals.append(frameParams[1]->rxBeamFormerNumber); + mlaVals.append(frameParams[1]->rxBeamFormerNumber); + mlaVals.append(frameParams[0]->rxBeamFormerNumber); + mlaVals.append(frameParams[0]->rxBeamFormerNumber); + } + else + { + rxBeamFormerTypeNumber = 2; + + mlaVals.append(frameParams[1]->rxBeamFormerNumber); + mlaVals.append(frameParams[0]->rxBeamFormerNumber); + } + + auto lag = Calculation::lag(rxBeamFormerTypeNumber, + hardwareOuput.hwRegister.pulseProps, + probeParams.getProbeProps().impulseResponse); + + for(auto i = 0; i < rxBeamFormerTypeNumber; i++) + { + RxBeamFormer_t temp; + temp.mla = mlaVals[i]; + temp.apodizationSel = apodizationSel; + temp.lag = roundf(lag[i] * fpgaTxDt / delayCalcDt); + hardwareOuput.hwRegister.rxBeamFormerProps.append(temp); + } + + hardwareOuput.hwRegister.rxBeamFormerTypeNumber = rxBeamFormerTypeNumber; +} + +/*************************************************************************************************/ +void BmModeScenario::calcReceiverConfigProperties() +{ + hardwareOuput.hwRegister.receiverConfigProps.clear(); + + auto receiverConfigTypeNumber = 2; + + QList lineModeVals = {1, 2}; + QList stbEnVals = {true, false}; + QList lineFilterEnVals = {true, false}; + + for(auto i = 0; i < receiverConfigTypeNumber; i++) + { + ReceiverConfig_t temp; + temp.lineMode = lineModeVals[i]; + temp.stbEn = stbEnVals[i]; + temp.lineFilterEn = lineFilterEnVals[i]; + temp.mla = frameParams[i]->mla; + temp.aTgcSel = 1; + temp.stb = frameParams[i]->stb; + temp.subtractFilterEn = userParams.pulseInversion; + temp.dcCancelEn = true; + temp.ncoFreqSel = 1; + temp.lpfSel = 1; + temp.absEn = true; + temp.focusNo = 1; + temp.ddcn = true; + hardwareOuput.hwRegister.receiverConfigProps.append(temp); + } + + hardwareOuput.hwRegister.receiverConfigTypeNumber = receiverConfigTypeNumber; +} + +/*************************************************************************************************/ +void BmModeScenario::calcFreqLut() +{ + hardwareOuput.hwRegister.freqLut = frameParams[0]->f0; +} diff --git a/src/model/scenarioGenerator/core/scenario/type/frame/BFrame.cpp b/src/model/scenarioGenerator/core/scenario/type/frame/BFrame.cpp new file mode 100644 index 0000000..5ce1b34 --- /dev/null +++ b/src/model/scenarioGenerator/core/scenario/type/frame/BFrame.cpp @@ -0,0 +1,181 @@ +#include "model/scenarioGenerator/core/scenario/type/frame/BFrame.h" + +#include "model/scenarioGenerator/core/general/Calculation.h" + +void BFrame::setFocusAx() +{ + QVector tempFocusAx; + if(_userParams.focusFrequencyCompound) + { + tempFocusAx = Calculation::zeros(2); + tempFocusAx[0] = _probeParams.getProbeProps().ffcValues[0][_userParams.focus]; + tempFocusAx[1] = _probeParams.getProbeProps().ffcValues[1][_userParams.focus]; + } + else + { + tempFocusAx = Calculation::zeros(_userParams.focusNumber); + if(_userParams.harmonicImaging) + { + for(auto i = 0; i < _userParams.focusNumber; i++) + { + tempFocusAx[i] = + _probeParams.getProbeProps().hiFocusValues[_userParams.focus + i * + _probeParams.getProbeProps(). + multiFocusStep]; + } + } + else + { + for(auto i = 0; i < _userParams.focusNumber; i++) + { + tempFocusAx[i] = + _probeParams.getProbeProps().focusValues[_userParams.focus + i * + _probeParams.getProbeProps(). + multiFocusStep]; + } + } + } + + focusNumber = _userParams.focusNumber; + focusAx = tempFocusAx; + ffc = _userParams.focusFrequencyCompound; +} + +/*************************************************************************************************/ +void BFrame::setScan() +{ + auto steeringCos = cosf(steering); + + if(_userParams.hdZoom) + { + maxScanAx = _userParams.maxScanAx / steeringCos; + minScanAx = _userParams.minScanAx / steeringCos; + maxScanAz = _userParams.maxScanAz; + minScanAz = _userParams.minScanAz; + } + else + { + maxScanAx = _userParams.depth / steeringCos; + minScanAx = _sysParams.startDepth; + maxScanAz = _probeParams.getScndProbeProps().fieldOfView / 2; + minScanAz = -_probeParams.getScndProbeProps().fieldOfView / 2; + } + + rangeAx = maxScanAx - minScanAx; + rangeAz = maxScanAz - minScanAz; +} + +/*************************************************************************************************/ +void BFrame::setMlaStb() +{ + //TODO: read from preset + stb = 0;//_sysParams.stb; + mla = 1;//_sysParams.mla; +} + +/*************************************************************************************************/ +void BFrame::setSteering(quint32 frameIndex) +{ + steering = _probeParams.getProbeProps().criSteeringAngles[_userParams.cri][frameIndex]; +} + +/*************************************************************************************************/ +void BFrame::setFrequency() +{ + auto fpgaTxDt = _sysParams.fpgaTxDt; + auto focus = _userParams.focus; + auto frequency = _userParams.frequency; + + halfPeriod = Calculation::zeros(_userParams.focusFrequencyCompound ? 2 : 1); + + if(_userParams.focusFrequencyCompound) + { + halfPeriod[0] = + static_cast(roundf(1.0f / 2.0f / + _probeParams.getProbeProps().ffcValues[2][focus] / + fpgaTxDt)); + halfPeriod[1] = + static_cast(roundf(1.0f / 2.0f / + _probeParams.getProbeProps().ffcValues[3][focus] / + fpgaTxDt)); + } + else if(_userParams.harmonicImaging) + { + halfPeriod[0] = + static_cast(roundf(1.0f / 2.0f / + _probeParams.getProbeProps().hiFrequencyValues[frequency] / + fpgaTxDt)); + } + else + { + halfPeriod[0] = + static_cast(roundf(1.0f / 2.0f / + _probeParams.getProbeProps().frequencyValues[frequency] / + fpgaTxDt)); + } + + f0 = Calculation::zeros(halfPeriod.length()); + for(auto i = 0; i < halfPeriod.length(); i++) + { + f0[i] = 1.0f / 2.0f / fpgaTxDt / halfPeriod[i]; + } +} + +/*************************************************************************************************/ +void BFrame::setLineDensity() +{ + if(_userParams.virtualConvex) + { + lineDensity = _probeParams.getProbeProps().virtualConvexLineDensityValues[ + _userParams.lineDensity]; + } + else + { + lineDensity = _probeParams.getProbeProps().lineDensityValues[_userParams.lineDensity]; + } +} + +/*************************************************************************************************/ +void BFrame::setShotPerLine() +{ + auto focusNo = _userParams.focusNumber; + + if(_userParams.focusFrequencyCompound) + { + shotPerLine = 2; + } + else if(_userParams.pulseInversion) + { + shotPerLine = 2 * focusNo; + } + else + { + shotPerLine = focusNo; + } +} + +/*************************************************************************************************/ +void BFrame::setPriExtension() +{ + if(_userParams.bMQuality) + { + priExtension = _probeParams.getProbeProps().priExtensionValue[0]; + } + else + { + priExtension = _probeParams.getProbeProps().priExtensionValue[1]; + } +} + +/*************************************************************************************************/ +BFrame::BFrame(ScenGenUserParameters_t userParams, + ScenGenSystemParameters_t sysParams, + ScenGenProbeParameters_t probeParams) : + BaseFrame(userParams, sysParams, probeParams) +{ +} + +/*************************************************************************************************/ +BFrame::~BFrame() +{ +} diff --git a/src/model/scenarioGenerator/core/scenario/type/frame/BaseFrame.cpp b/src/model/scenarioGenerator/core/scenario/type/frame/BaseFrame.cpp new file mode 100644 index 0000000..829afb9 --- /dev/null +++ b/src/model/scenarioGenerator/core/scenario/type/frame/BaseFrame.cpp @@ -0,0 +1,622 @@ +#include "model/scenarioGenerator/core/scenario/type/frame/BaseFrame.h" + +#include "model/scenarioGenerator/core/general/Calculation.h" +#include "model/scenarioGenerator/core/general/AperturePosition.h" +#include "model/scenarioGenerator/core/general/InterceptFocus.h" +#include "model/backendImageProcessor/core/algorithm/ScanConversionAlg.h" +#include "model/scenarioGenerator/core/general/MinMaxDelay.h" + +#include "math.h" + +void BaseFrame::setC0dRdAx() +{ + c0 = _probeParams.getProbeProps().otiC0Values[_userParams.oti]; + dR = c0 * _sysParams.delayCalcDt; + rxPointDax = c0 * _sysParams.lineDt / 2; +} + +/*************************************************************************************************/ +void BaseFrame::setShotLineNumber() +{ + auto maxBPulseNo = _sysParams.maxBPulseNumber; + + txLineNumber = + Calculation::linearSpaceInterval(rangeAz, 1 / lineDensity, maxBPulseNo).first; + + txShotNumber = txLineNumber * shotPerLine; + rxLineNumber = txLineNumber * mla; + if(rxLineNumber > 1) + { + rxLineDaz = rangeAz / (rxLineNumber - 1); + } + else + { + rxLineDaz = 0; + } +} + +/*************************************************************************************************/ +void BaseFrame::setRxFocusPointNumber() +{ + rxFocusPointNumber = Calculation::linearSpaceDistance(rangeAx, + rxPointDax, + _sysParams.maxRxFocusPointNumber).first; + rxFocusPointNumber += (rxFocusPointNumber % 2); +} + +/*************************************************************************************************/ +void BaseFrame::setFocusR() +{ + focusR.clear(); + + if(_probeParams.getProbeProps().linear) + { + if(_userParams.virtualConvex) + { + QVector x; + for(auto i = 0; i < focusAx.length(); i++) + { + x.push_back(0); + } + focusR = ScanConversionAlg::virtualScanConversion(x, + focusAx, + steering, + _probeParams.getScndProbeProps().virtualOriginalZ, + _sysParams.startDepth, + _userParams.depth, + _probeParams.getScndProbeProps().vcMaxTheta) + .first; + } + else + { + for(auto i = 0; i < focusAx.length(); i++) + { + focusR.push_back(focusAx[i] / cos(steering)); + } + } + } + else + { + QVector x; + QVector z; + for(auto i = 0; i < focusAx.length(); i++) + { + x.push_back(0); + z.push_back(focusAx[i] + _probeParams.getProbeProps().radius); + } + focusR = ScanConversionAlg::convexScanConversion(x, + z, + steering, + _userParams.angle, + _probeParams.getScndProbeProps().fieldOfView, + _probeParams.getProbeProps().radius, + _sysParams.startDepth, + _userParams.depth).first; + for(auto i = 0; i < focusAx.length(); i++) + { + focusR[i] -= _probeParams.getProbeProps().radius; + } + } + + focusR = Calculation::repMat(focusR, txLineNumber); +} + +/*************************************************************************************************/ +void BaseFrame::setPulseInterval() +{ + pulseInterval = 2 * maxScanAx / c0 + priExtension; +} + +/*************************************************************************************************/ +void BaseFrame::setOtherParameters() +{ + rxBeamFormerNumber = mla + 2 * stb; + rxStbLineNumber = txLineNumber * rxBeamFormerNumber; + focusTypeNumber = txLineNumber * focusNumber; + + auto temp = Calculation::linearSpace(minScanAz + (mla - 1) / 2 * rxLineDaz, + maxScanAz - (mla - 1) / 2 * rxLineDaz, + txLineNumber); + + interceptAz = Calculation::repElem(temp, focusNumber); + + r0Az = Calculation::linearSpace(minScanAz - stb * rxLineDaz, + maxScanAz + stb * rxLineDaz, + rxLineNumber + 2 * stb); + + if(ffc) + { + txF0 = Calculation::repElem(f0, txLineNumber); + } + else + { + txF0 = Calculation::repElem(f0, txLineNumber * focusNumber); + } + + rxF0 = Calculation::repMat(f0, rxStbLineNumber); +} + +/*************************************************************************************************/ +void BaseFrame::setInterceptFocus() +{ + InterceptFocus f(_probeParams, interceptAz, focusR, steering, dR); + auto res = f.getInterceptFocus(); + txInterceptPoint = res.first; + focusPoint = res.second; + + InterceptFocus f2(_probeParams, r0Az, {minScanAx}, steering, dR); + res = f2.getInterceptFocus(); + rxInterceptPoint = res.first; + r0Point = res.second; +} + +/*************************************************************************************************/ +void BaseFrame::setAperture() +{ + { + QVector fNumber; + for(auto i = 0; i < txF0.length(); i++) + { + fNumber.push_back(1.2f * c0 / txF0[i] / _probeParams.getProbeProps().txResolution); + } + auto txActiveElementNumber = rxApertureSize(fNumber, focusPoint); + Apertureposition ap; + txAperture.startActiveElementNumber = ap.getAperturePosition(_probeParams, + txActiveElementNumber, + txInterceptPoint).first; + txAperture.activeElementNumber = txActiveElementNumber; + } + + { + QVector fNumber; + for(auto i = 0; i < rxF0.length(); i++) + { + fNumber.push_back(1.2f * c0 / rxF0[i] / _probeParams.getProbeProps().rxResolution); + } + auto rxActiveElementNumber = rxApertureSize(fNumber, r0Point); + Apertureposition ap; + auto res = ap.getAperturePosition(_probeParams, + rxActiveElementNumber, + rxInterceptPoint); + rxAperture.startActiveElementNumber = res.first; + rxAperture.centerActiveElementNumber = res.second; + rxAperture.activeElementNumber = rxActiveElementNumber; + } +} + +/*************************************************************************************************/ +void BaseFrame::setMinMaxDelay() +{ + MinMaxDelay mmd(_probeParams, txAperture, focusPoint); + + auto tempDelay = mmd.getMinMaxDelay(); + + auto delayCalcDt = _sysParams.delayCalcDt; + auto fpgaTxDt = _sysParams.fpgaTxDt; + + for(auto i = 0; i < tempDelay.minDelay.length(); i++) + { + tempDelay.minDelay[i] = roundf(tempDelay.minDelay[i] * delayCalcDt / fpgaTxDt); + } + + for(auto i = 0; i < tempDelay.maxDelay.length(); i++) + { + tempDelay.maxDelay[i] = roundf(tempDelay.maxDelay[i] * delayCalcDt / fpgaTxDt); + } + + for(auto i = 0; i < tempDelay.maxDelayQ.length(); i++) + { + tempDelay.maxDelayQ[i] = roundf(tempDelay.maxDelayQ[i] * delayCalcDt / fpgaTxDt); + } + + MinMaxDelay mmd2(_probeParams, rxAperture, r0Point); + + auto delayRx = mmd2.getMinMaxDelay(); + + QVector txInterceptXPos; + QVector txInterceptYPos; + QVector txInterceptZPos; + if(focusNumber > 1 && !ffc) + { + for(auto i = 0; i < txInterceptPoint.length(); i += focusNumber) + { + txInterceptXPos.append(txInterceptPoint[i].x); + txInterceptYPos.append(txInterceptPoint[i].y); + txInterceptZPos.append(txInterceptPoint[i].z); + } + } + else + { + for(auto i = 0; i < txInterceptPoint.length(); i++) + { + txInterceptXPos.append(txInterceptPoint[i].x); + txInterceptYPos.append(txInterceptPoint[i].y); + txInterceptZPos.append(txInterceptPoint[i].z); + } + } + + txInterceptXPos = Calculation::repElem(txInterceptXPos, rxBeamFormerNumber); + txInterceptYPos = Calculation::repElem(txInterceptYPos, rxBeamFormerNumber); + txInterceptZPos = Calculation::repElem(txInterceptZPos, rxBeamFormerNumber); + + QVector r0XPosition; + QVector r0YPosition; + QVector r0ZPosition; + + QVector txR0MinDelay; + for(auto i = 0; i < r0Point.length(); i++) + { + r0XPosition.append(r0Point[i].x); + r0YPosition.append(r0Point[i].y); + r0ZPosition.append(r0Point[i].z); + + auto temp = sqrtf(powf(r0Point[i].x - txInterceptXPos[i], 2.0f) + + powf(r0Point[i].y - txInterceptYPos[i], 2.0f) + + powf(r0Point[i].z - txInterceptZPos[i], 2.0f)); + txR0MinDelay.append(temp); + } + + auto r0XPositionQ = Calculation::qntzr(r0XPosition, 1, 18, 0, 0, true, true); + auto r0YPositionQ = Calculation::qntzr(r0YPosition, 1, 18, 0, 0, true, true); + auto r0ZPositionQ = Calculation::qntzr(r0ZPosition, 0, 17, 0, 0, true, true); + auto txInterceptXPosQ = Calculation::qntzr(txInterceptXPos, 1, 18, 0, 0, true, true); + auto txInterceptYPosQ = Calculation::qntzr(txInterceptYPos, 1, 18, 0, 0, true, true); + auto txInterceptZPosQ = Calculation::qntzr(txInterceptZPos, 0, 17, 0, 0, true, true); + + QVector txR0MinDelayQ; + for(auto i = 0; i < r0Point.length(); i++) + { + auto temp = roundf(sqrtf(powf(r0XPositionQ[i] - txInterceptXPosQ[i], 2.0f) + + powf(r0YPositionQ[i] - txInterceptYPosQ[i], 2.0f) + + powf(r0ZPositionQ[i] - txInterceptZPosQ[i], 2.0f))); + txR0MinDelayQ.append(temp); + } + + delay.minDelay = tempDelay.minDelay; + delay.maxDelay = tempDelay.maxDelay; + delay.maxDelayQ = tempDelay.maxDelayQ; + delay.rxR0MaxDelay = delayRx.maxDelay; + delay.rxR0MaxDelayQ = delayRx.maxDelayQ; + delay.rxR0MinDelay = delayRx.minDelay; + delay.rxR0MinDelayQ = delayRx.minDelayQ; + delay.txR0MinDelay = txR0MinDelay; + delay.txR0MinDelayQ = txR0MinDelayQ; +} + +/*************************************************************************************************/ +void BaseFrame::setInterceptPointFiringTime() +{ + auto maxDelay = delay.maxDelay; + auto delayCalcDt = _sysParams.delayCalcDt; + auto fpgaTxDt = _sysParams.fpgaTxDt; + + for(auto i = 0; i < focusR.length(); i++) + { + interceptPointFiringTime.append(static_cast(roundf( + maxDelay[i] * fpgaTxDt / + delayCalcDt - focusR[i] / dR))); + } +} + +/*************************************************************************************************/ +void BaseFrame::setRxActiveElementStep() +{ + rxActiveElementStep.clear(); + + for(auto i = 0; i < txF0.length(); i++) + { + auto fNumber = 1.2f * c0 / txF0[i] / _probeParams.getProbeProps().rxResolution; + rxActiveElementStep.append( + 255 * rxPointDax / fNumber / _probeParams.getScndProbeProps().pitchAzimuth); + } +} + +/*************************************************************************************************/ +void BaseFrame::repeatMultiFocus() +{ + QVector rxInterceptXPos; + QVector rxInterceptYPos; + QVector rxInterceptZPos; + QVector r0XPosition; + QVector r0YPosition; + QVector r0ZPosition; + QVector theta; + float r0R; + + for(auto i = 0; i < rxInterceptPoint.length(); i++) + { + rxInterceptXPos.append(rxInterceptPoint[i].x); + rxInterceptYPos.append(rxInterceptPoint[i].y); + rxInterceptZPos.append(rxInterceptPoint[i].z); + } + + r0R = r0Point[0].r; + for(auto i = 0; i < r0Point.length(); i++) + { + r0XPosition.append(r0Point[i].x); + r0YPosition.append(r0Point[i].y); + r0ZPosition.append(r0Point[i].z); + theta.append(r0Point[i].theta); + } + + if(!ffc && focusNumber > 1) + { + theta = Calculation::repElem(theta, focusNumber); + delay.rxR0MinDelay = Calculation::repElem(delay.rxR0MinDelay, focusNumber); + delay.rxR0MaxDelay = Calculation::repElem(delay.rxR0MaxDelay, focusNumber); + delay.rxR0MinDelayQ = Calculation::repElem(delay.rxR0MinDelayQ, focusNumber); + delay.rxR0MaxDelayQ = Calculation::repElem(delay.rxR0MaxDelayQ, focusNumber); + rxAperture.activeElementNumber = Calculation::repElem(rxAperture.activeElementNumber, + focusNumber); + rxAperture.centerActiveElementNumber = Calculation::repElem( + rxAperture.centerActiveElementNumber, + focusNumber); + rxInterceptXPos = Calculation::repElem(rxInterceptXPos, focusNumber); + rxInterceptYPos = Calculation::repElem(rxInterceptYPos, focusNumber); + rxInterceptZPos = Calculation::repElem(rxInterceptZPos, focusNumber); + delay.txR0MinDelay = Calculation::repElem(delay.txR0MinDelay, focusNumber); + delay.txR0MinDelayQ = Calculation::repElem(delay.txR0MinDelayQ, focusNumber); + rxAperture.startActiveElementNumber = Calculation::repElem( + rxAperture.startActiveElementNumber, + focusNumber); + r0XPosition = Calculation::repElem(r0XPosition, focusNumber); + r0YPosition = Calculation::repElem(r0YPosition, focusNumber); + r0ZPosition = Calculation::repElem(r0ZPosition, focusNumber); + } + + rxInterceptPoint.clear(); + for(auto i = 0; i < rxInterceptXPos.length(); i++) + { + Point_t temp; + temp.x = rxInterceptXPos[i]; + temp.y = rxInterceptYPos[i]; + temp.z = rxInterceptZPos[i]; + temp.theta = theta[i]; + rxInterceptPoint.append(temp); + } + + r0Point.clear(); + for(auto i = 0; i < r0XPosition.length(); i++) + { + Point_t temp; + temp.x = r0XPosition[i]; + temp.y = r0YPosition[i]; + temp.z = r0ZPosition[i]; + temp.theta = theta[i]; + temp.r = r0R; + r0Point.append(temp); + } +} + +/*************************************************************************************************/ +void BaseFrame::repeatRxInterceptR0() +{ + QVector rxInterceptXPosTemp; + QVector rxInterceptYPosTemp; + QVector rxInterceptZPosTemp; + QVector rxInterceptAzTemp; + QVector r0XPositionTemp; + QVector r0YPositionTemp; + QVector r0ZPositionTemp; + QVector r0AzTemp; + QVector thetaTemp; + float r0R; + + for(auto i = 0; i < rxInterceptPoint.length(); i++) + { + rxInterceptXPosTemp.push_back(rxInterceptPoint[i].x); + rxInterceptYPosTemp.push_back(rxInterceptPoint[i].y); + rxInterceptZPosTemp.push_back(rxInterceptPoint[i].z); + rxInterceptAzTemp.push_back(rxInterceptPoint[i].azimuth); + } + + r0R = r0Point[0].r; + for(auto i = 0; i < r0Point.length(); i++) + { + r0XPositionTemp.push_back(r0Point[i].x); + r0YPositionTemp.push_back(r0Point[i].y); + r0ZPositionTemp.push_back(r0Point[i].z); + r0AzTemp.push_back(r0Point[i].azimuth); + thetaTemp.push_back(r0Point[i].theta); + } + + QVector rxInterceptXPos; + QVector rxInterceptYPos; + QVector rxInterceptZPos; + QVector r0XPosition; + QVector r0YPosition; + QVector r0ZPosition; + QVector rxInterceptAzimuth; + QVector r0Azimuth; + QVector theta; + + if(stb > 0) + { + for(auto i = 0; i < rxStbLineNumber; i++) + { + rxInterceptXPos.push_back(1); + rxInterceptYPos.push_back(1); + rxInterceptZPos.push_back(1); + r0XPosition.push_back(1); + r0YPosition.push_back(1); + r0ZPosition.push_back(1); + rxInterceptAzimuth.push_back(1); + r0Azimuth.push_back(1); + theta.push_back(1); + } + + for(auto i = 0; i < txLineNumber; i++) + { + QList rxLineNum1; + for(auto j = i * mla; j < (i + 1) * mla + 2 * stb; j++) + { + rxLineNum1.append(j); + } + + QList rxLineNum2; + for(auto j = i * rxBeamFormerNumber; j < (i + 1) * rxBeamFormerNumber; j++) + { + rxLineNum2.append(j); + } + + for(auto j = 0; j < rxLineNum1.length(); j++) + { + auto d = rxLineNum2[j]; + auto s = rxLineNum1[j]; + rxInterceptXPos[d] = rxInterceptXPosTemp[s]; + rxInterceptYPos[d] = rxInterceptYPosTemp[s]; + rxInterceptZPos[d] = rxInterceptZPosTemp[s]; + r0XPosition[d] = r0XPositionTemp[s]; + r0YPosition[d] = r0YPositionTemp[s]; + r0ZPosition[d] = r0ZPositionTemp[s]; + rxInterceptAzimuth[d] = rxInterceptAzTemp[s]; + r0Azimuth[d] = r0AzTemp[s]; + theta[d] = thetaTemp[s]; + } + } + } + else + { + rxInterceptXPos = rxInterceptXPosTemp; + rxInterceptYPos = rxInterceptYPosTemp; + rxInterceptZPos = rxInterceptZPosTemp; + r0XPosition.append(r0XPositionTemp); + r0YPosition.append(r0YPositionTemp); + r0ZPosition.append(r0ZPositionTemp); + rxInterceptAzimuth = rxInterceptAzTemp; + r0Azimuth = r0AzTemp; + theta = thetaTemp; + } + + if(ffc) + { + rxInterceptXPos = Calculation::repElem(rxInterceptXPos, 2); + rxInterceptYPos = Calculation::repElem(rxInterceptYPos, 2); + rxInterceptZPos = Calculation::repElem(rxInterceptZPos, 2); + r0XPosition = Calculation::repElem(r0XPosition, 2); + r0YPosition = Calculation::repElem(r0YPosition, 2); + r0ZPosition = Calculation::repElem(r0ZPosition, 2); + rxInterceptAzimuth = Calculation::repElem(rxInterceptAzimuth, 2); + r0Azimuth = Calculation::repElem(r0Azimuth, 2); + theta = Calculation::repElem(theta, 2); + } + + rxInterceptPoint.clear(); + for(auto i = 0; i < rxInterceptXPos.length(); i++) + { + Point_t temp; + temp.x = rxInterceptXPos[i]; + temp.y = rxInterceptYPos[i]; + temp.z = rxInterceptZPos[i]; + temp.theta = theta[i]; + temp.azimuth = rxInterceptAzimuth[i]; + rxInterceptPoint.append(temp); + } + + r0Point.clear(); + for(auto i = 0; i < r0XPosition.length(); i++) + { + Point_t temp; + temp.x = r0XPosition[i]; + temp.y = r0YPosition[i]; + temp.z = r0ZPosition[i]; + temp.theta = theta[i]; + temp.azimuth = r0Azimuth[i]; + temp.r = r0R; + r0Point.append(temp); + } +} + +/*************************************************************************************************/ +QVector BaseFrame::rxApertureSize(QVector fNumber, QList points) +{ + auto elementNo = _probeParams.getProbeProps().elementNo; + auto pitch = _probeParams.getProbeProps().pitch; + auto radius = _probeParams.getProbeProps().radius; + auto linear = _probeParams.getProbeProps().linear; + auto channelNo = _sysParams.channelNumber; + + auto maxApertureSize = qMin(channelNo, elementNo); + + QVector activeElementNumber; + quint32 temp; + for(auto i = 0; i < fNumber.length(); i++) + { + if(linear) + { + if(points.length() == 1) + { + temp = ceilf(fNumber[i] * points[0].r / pitch); + } + else + { + temp = ceilf(fNumber[i] * points[i].r / pitch); + } + } + else + { + if(points.length() == 1) + { + temp = ceilf(fNumber[i] * points[0].r / (radius + points[0].r) / pitch); + } + else + { + temp = ceilf(fNumber[i] * points[i].r / (radius + points[i].r) / pitch); + } + } + + if(temp < 1) + { + temp = 1; + } + + if(temp > maxApertureSize) + { + temp = maxApertureSize; + } + + activeElementNumber.push_back(temp); + } + + return activeElementNumber; +} + +/*************************************************************************************************/ +BaseFrame::BaseFrame(ScenGenUserParameters_t userParams, + ScenGenSystemParameters_t sysParams, + ScenGenProbeParameters_t probeParams) +{ + _userParams = userParams; + _sysParams = sysParams; + _probeParams = probeParams; +} + +BaseFrame::~BaseFrame() +{ +} + +/*************************************************************************************************/ +void BaseFrame::setParameters(quint32 frameIndex) +{ + setC0dRdAx(); + setSteering(frameIndex); + setScan(); + setShotPerLine(); + setMlaStb(); + setLineDensity(); + setPriExtension(); + setFocusAx(); + setFrequency(); + setShotLineNumber(); + setRxFocusPointNumber(); + setFocusR(); + setPulseInterval(); + setOtherParameters(); + setInterceptFocus(); + repeatRxInterceptR0(); + setAperture(); + setMinMaxDelay(); + setInterceptPointFiringTime(); + setRxActiveElementStep(); + repeatMultiFocus(); +} diff --git a/src/model/scenarioGenerator/core/scenario/type/frame/MFrame.cpp b/src/model/scenarioGenerator/core/scenario/type/frame/MFrame.cpp new file mode 100644 index 0000000..9828856 --- /dev/null +++ b/src/model/scenarioGenerator/core/scenario/type/frame/MFrame.cpp @@ -0,0 +1,93 @@ +#include "model/scenarioGenerator/core/scenario/type/frame/MFrame.h" + +MFrame::MFrame(ScenGenUserParameters_t userParams, + ScenGenSystemParameters_t sysParams, + ScenGenProbeParameters_t probeParams) : + BaseFrame(userParams, sysParams, probeParams) +{ +} + +MFrame::~MFrame() +{ +} + +/*************************************************************************************************/ +void MFrame::setFocusAx() +{ + focusNumber = 1; + + focusAx.clear(); + if(_userParams.harmonicImaging) + { + focusAx.append(_probeParams.getProbeProps().hiFocusValues[_userParams.focus]); + } + else + { + focusAx.append(_probeParams.getProbeProps().focusValues[_userParams.focus]); + } +} + +/*************************************************************************************************/ +void MFrame::setScan() +{ + maxScanAx = _userParams.depth; + minScanAx = _sysParams.startDepth; + maxScanAz = _userParams.mLineAzimuth; + minScanAz = _userParams.mLineAzimuth; + + rangeAx = maxScanAx = minScanAx; + rangeAz = maxScanAz = minScanAz; +} + +/*************************************************************************************************/ +void MFrame::setMlaStb() +{ + mla = 1; + stb = 0; +} + +/*************************************************************************************************/ +void MFrame::setSteering(quint32 frameIndex) +{ + steering = 0; +} + +/*************************************************************************************************/ +void MFrame::setFrequency() +{ + float freq; + if(_userParams.pulseInversion) + { + freq = _probeParams.getProbeProps().hiFrequencyValues[_userParams.frequency]; + } + else + { + freq = _probeParams.getProbeProps().frequencyValues[_userParams.frequency]; + } + + halfPeriod.clear(); + halfPeriod.append(roundf(1 / 2 / freq / _sysParams.fpgaTxDt)); + + f0.clear(); + f0.append(1 / 2 / _sysParams.fpgaTxDt / halfPeriod[0]); +} + +/*************************************************************************************************/ +void MFrame::setLineDensity() +{ + lineDensity = 0; +} + +/*************************************************************************************************/ +void MFrame::setShotPerLine() +{ + shotPerLine = 1; +} + +/*************************************************************************************************/ +void MFrame::setPriExtension() +{ + auto priExtensionIndex = _userParams.bMQuality ? 0 : 1; + + priExtension = _probeParams.getProbeProps().priExtensionValue[priExtensionIndex]; +}